I have a table, 6 columns, the 6th column is empty but the other 5 have data. I used the 4th and 5th columns to calculate a value and then I wish to insert this value into the 6th column.
This is what I have so far:
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
EDIT: The above code hasn’t worked. It has set the same value for every single row regardless of the primary key….
Does this solve your problem?
To get the right rows, use a WHERE statement.