I need to update the second record AFS_OH column (ForecastID =23) with the previous AFS_ToProduce value (ForecastID = 22) from the first record below. In otherwords the second record value for AFS_OH = 307923.
Also, I need to update these values for the entire table so I the ForecastID numbers will differ based on the criteria of AFS_ToProduce < 0 as you will notice in my WHERE clause below.
My script below is updating the same record value instead of the following record. Thanks for your help!
ForecastID AFS_OH AFS_ToProduce
22 307923 -307923
23 0 316602
Here’s my approach:
UPDATE FC_Test
SET AFS_OH = (AFS_ToProduce * (-1))
FROM FC_Test S3
INNER JOIN
(
SELECT S1.FORECASTID, S2.AFS_ToProduce AS AFS_OH
FROM FC_Test S1
LEFT OUTER JOIN
(
SELECT *
FROM FC_Test
) S2
ON S1.ForecastID = S2.ForecastID
)S4 ON S3.ForecastID = S4.ForecastID
WHERE AFS_ToProduce < 0
The following update will transfer negative value of AFS_ToProduce to next row if next row has positive AFS_ToProduce. If not, this row will be ignored.
Inner
select top 1will retrieve previous row if AFS_ToProduce is negative; if not, current row from fc_test will be skipped. This allows for gaps in ForecastID.TEST is here on Sql Fiddle.