0

我有一个表,6 列,第 6 列是空的,但其他 5 列有数据。我使用第 4 列和第 5 列来计算一个值,然后我希望将此值插入到第 6 列中。

这是我到目前为止所拥有的:

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

编辑:上面的代码没有工作。无论主键如何,它都为每一行设置了相同的值....

4

2 回答 2

1

这能解决你的问题吗?

UPDATE Table_Name SET Column6 = Column4 + Column5

要获得正确的行,请使用 WHERE 语句。

于 2012-05-21T14:47:47.093 回答
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'
于 2012-05-21T14:48:04.703 回答