2012-05-21 72 views
0

我有一個表,6列,第6列是空的,但其他5有數據。我用第四和第五列來計算一個值,然後我希望將這個值插入第六列。用SELECT語句中的計算值更新空列?

這是我到目前爲止有:

UPDATE Table_Name 
SET Change = tab3.Difference 
FROM 
    (SELECT COBDate, FileName, ID, ScenarioID FROM Table_Name WHERE COBDate = '2012-05-18' AND FileName = 'GBP.csv') tab0 
INNER JOIN 
    (SELECT tab1.ID, tab1.ScenarioID,tab1.COBDate, tab1.FileName, Val1 - Val2 AS Difference FROM 
     (SELECT COBDate, FileName, ScenarioID, ID, CASE WHEN Value IS NULL THEN 0 ELSE Value END AS Val1 FROM Table_Name WHERE COBDate = '2012-05-18' AND FileName = 'GBP.csv') tab1 
    JOIN 
     (SELECT COBDate, FileName, ScenarioID, ID, CASE WHEN Value IS NULL THEN 0 ELSE Value END AS Val2 FROM Table_Name WHERE COBDate = '2012-05-17' AND FileName = 'GBP.csv') tab2 
    ON tab1.ScenarioID = tab2.ScenarioID AND tab1.ID = tab2.ID) tab3 
ON tab0.COBDate = tab3.COBDate 
AND tab0.FileName = tab3.FileName 
AND tab0.ID = tab3.ID 
AND tab0.ScenarioID = tab3.ScenarioID 

編輯:上面的代碼沒有奏效。它爲每一行設置了相同的值,而不管主鍵是什麼......

+1

請發佈您的'SELECT'查詢。 – bfavaretto

回答

1

這是否解決了您的問題?

UPDATE Table_Name SET Column6 = Column4 + Column5 

要獲得正確的行,請使用WHERE語句。

+0

嗨,我找到了我需要做的事(見編輯),但連接不起作用。它爲每行放置sam值,而不是tab3的值。 – mezamorphic

+0

如果不確定,請在UPDATE之前先執行SELECT。你的SELECT將反映你將要更新的行,然後你可以調整你的WHERE子句來獲得正確的行,並確保你沒有搞亂你的數據庫。 – Charleh

+0

嗨Charleh,在SET行下面我已經包含了SELECT *,並且在它下面運行SQL時,它顯示了每行的差異值是正確的。 – mezamorphic

0

重寫您的語句,使得from語句直接引用您正在更新的表。例如,使用where子句刪除您的第一個子查詢,如下所示:

UPDATE Table_Name 
SET Change = tab3.Difference 
FROM Table_Name tab0 

    INNER JOIN  

    (SELECT tab1.ID, tab1.ScenarioID,tab1.COBDate, tab1.FileName, Val1 - Val2 AS Difference 
     FROM 
      (SELECT COBDate, FileName, ScenarioID, ID, CASE WHEN Value IS NULL THEN 0 ELSE Value END AS Val1 
      FROM Table_Name 
      WHERE COBDate = '2012-05-18' AND FileName = 'GBP.csv' 
     ) tab1  
     JOIN   
      (SELECT COBDate, FileName, ScenarioID, ID, CASE WHEN Value IS NULL THEN 0 ELSE Value END AS Val2 
      FROM Table_Name 
      WHERE COBDate = '2012-05-17' AND FileName = 'GBP.csv' 
     ) tab2 ON 
       tab1.ScenarioID = tab2.ScenarioID 
       AND tab1.ID = tab2.ID 
    ) tab3 ON 

    tab0.COBDate = tab3.COBDate 
    AND tab0.FileName = tab3.FileName 
    AND tab0.ID = tab3.ID 
    AND tab0.ScenarioID = tab3.ScenarioID 

WHERE tab0.COBDate = '2012-05-18' 
    and tab0.FileName = 'GBP.csv' 
+0

包含我的select語句,但連接不起作用 – mezamorphic