简体   繁体   中英

Update SQL Server table record field with data from previous record

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 1 will retrieve previous row if AFS_ToProduce is negative; if not, current row from fc_test will be skipped. This allows for gaps in ForecastID.

update fc_test
set AFS_OH = - fc2.AFS_ToProduce
from fc_test
cross apply
(
  select fc2.AFS_ToProduce
  from 
  (
    select top 1
        fc2.AFS_ToProduce
      from fc_test fc2
     where fc2.ForecastID < fc_test.ForecastID
     order by fc2.ForecastID desc
  ) fc2
  where fc2.AFS_ToProduce < 0
) fc2
where fc_test.AFS_ToProduce > 0

TEST is here on Sql Fiddle .

Try this

DECLARE @tbl table (i int, p int)

INSERT INTO @tbl (i,p) VALUES (1,1),(10,10),(11,11),(20,20)

SELECT * FROM @tbl

UPDATE t1
SET t1.p=t2.p
FROM @tbl t1
     CROSS JOIN @tbl t2
WHERE t2.i=(SELECT max(i)
               FROM @tbl t
               WHERE i<t1.i)


SELECT * FROM @tbl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM