I have a weird update query to write.
Here’s the table
PK-ID (int) --- FK-ID (int) --- Value (int)
In my data set, if I group by FK-ID and order by PK-ID, suppose this is an example of one group:
5 --- 10 --- 23
7 --- 10 --- 49
8 --- 10 --- 81
Due to a bug in some old software, records 7 and 8 have incorrect values. The correct value for 7 is (49-23) = 26 and the correct value for 8 is (81-49) = 32. Record 5 is correct.
I need to update each record to subtract the value of the record immediately preceding it when it is grouped by FK-ID and ordered by PK-ID. If there is no preceding record I do not need to change the value.
Is there a way to write a general sql update query to accomplish this? How would I (conditionally) retrieve the value of the preceding record in the group? I’m using SQL server 2008.
Thanks!
1 Answer