Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading