SQL Server Set a value equal to the value of a sum from a row above?

6mw9ycah  于 2023-02-28  发布在  其他
关注(0)|答案(1)|浏览(145)

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.

q8l4jmvw

q8l4jmvw1#

You can use LAG along with OVER 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 the ORDER BY .

CREATE TABLE #t (Id INT IDENTITY(1,1), Transfer INT);
INSERT INTO #t (Transfer)
VALUES (12), (-2) , (-2) , (-1) , (-7);

WITH withRunningTotal AS(
    SELECT t.Id, SUM(t.Transfer) OVER (ORDER BY Id) AS RunningTotal, t.Transfer 
    FROM #t t
)
SELECT w.Id, COALESCE(LAG(w.RunningTotal) OVER (ORDER BY Id),0) Opening, w.Transfer
FROM withRunningTotal w;

DROP TABLE #t;

Results:

Id          Opening     Transfer
----------- ----------- -----------
1           0           12
2           12          -2
3           10          -2
4           8           -1
5           7           -7

相关问题