2012-04-20 157 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

相關問題