2012-04-20 149 views
0

我有两个表看起来如下SQL - 加入一个表与另一种基于(从第一表到第二表的列的值的行值)

第一表:

DealNum  CurrencyValue  CurrencyCode  Date 

    110    100     AA   01/12/2011 
    111    200     AB   01/11/2011 
    112    120     AC   01/10/2011 
    113    20     AA   01/11/2011 
    110    103     AD   01/12/2011 
    115    200     AD   01/11/2011 
    119    120     AG   01/10/2011 
    130    20     AK   01/11/2011 

第二表

CurrencyCode  OCT  NOV  DEC  JAN .. 

     AA    0.91  0.88  0.9  0.94 
     AB    0.9  0.8  0.96 0.89 
     AC    0.81  0.79  0.82 0.84 
     AD    0.4  0.41  0.42 0.39 
     AE    0.9  0.92  0.91 0.94 
     AF    0.8  0.82  0.83 0.81 

现在我想从第二个表中符合下列条件的数据添加到第一个表中的新列

1.It has to do based on the CurrencyCode and month 
2.If the deal is from DEC and currencyCode is AA , then it has to take the value 0.9, 
    if the deal is from NOV and currencyCode is AA , then it has to take the value 0.88.. 

所以,结果应该是这样的

DealNum  CurrencyValue  CurrencyCode  Date  NewColumn 

    110    100     AA   01/12/2011  0.9 
    111    200     AB   01/11/2011  0.8 
    112    120     AC   01/10/2011  0.81 
    113    20     AA   01/11/2011  0.88 
    110    103     AD   01/12/2011  0.42 
    115    200     AD   01/11/2011  0.41 
    119    120     AG   01/10/2011   -- 
    130    20     AK   01/11/2011   -- 

我对如何从第一台比较一个月的行值在第二个表月份的列值做到这一点毫无头绪。请帮我这个..

在此先感谢。

干杯, Harish。

回答

1

这应该工作,虽然你的第二张桌子设计不好。

SELECT DealNum  
     , CurrencyValue  
     , CurrencyCode  
     , Date 
     , Deal = 
     CASE MONTH(t1.Date) 
      WHEN 1 THEN t2.JAN 
      WHEN 2 THEN t2.FEB 
      WHEN 3 THEN t2.MAR 
      -- ..... 
      WHEN 10 THEN t2.OCT 
      WHEN 11 THEN t2.NOV 
      WHEN 12 THEN t2.DEC 
     END 
FROM Table1 t1 
INNER JOIN Table2 t2 ON t1.CurrencyCode = t2.CurrencyCode 
+0

感谢蒂姆Schmelter ..这是一个伟大的..对我工作的罚款。但是,这里的问题是第二个表中的列名(Months)每次都在不断变化,是否有任何动态的方式来执行此操作,如t1.date = t2。(XYZ month),然后t2.Jan或t2。二月???再次感谢你的帮助 :)) – harry 2012-04-20 16:27:07

相关问题