I have a table like this
| Opening | Transfer |
| ------------ | ------------ |
| 0 | 12 |
| 12 | -2 |
| 10 | -2 |
| 8 | -1 |
| 7 | -7 |
I need to recalculate this due to a gap in the real table.
I know the value of the opening will be the opening + transfer of the line above but how can I do this?
I've tried using a cursor but can't seem to make it work.
I've also tried using a while loop and setting an id to loop through each row but that doesn't seem to work either.
1条答案
按热度按时间q8l4jmvw1#
You can use
LAG
along withOVER
clause in SQL Server to accomplish what you're going for.Here is an example. Note that 1) you'll need something to reliably order by and 2) you may need to partition the data by using
PARTITION BY
in addition to theORDER BY
.Results: