0

I have a table with two columns (id and output). The output column can be positive and negative. Negative output means we need to refill. Positive output will reduce the refill.

In Excel I simply make a running sum of the output column and the sum of the refill column above the cell I am calculating.

Now I want to make the same calculation in SQL, but since I am new to SQL I can't really figure out how to do it.

In order to clarify my problem I have added an example below.

The Excel formula in cell C2 (Refill column) looks like this

=IF(SUM($B$2:B2)-SUM($C$1:C1)<0,SUM($B$2:B2)-SUM($C$1:C1),0)

In Cell C10 it looks like this

=IF(SUM($B$2:B10)-SUM($C$1:C9)<0,SUM($B$2:B10)-SUM($C$1:C9),0)

The output of the calculated column in Excel looks like below.

Does anyone know how to make this in SQL?

id      Output  Refill
1       -10     -10
2       -14     -14
3       0       0
4       8       0
5       0       0
6       -18     -10
7       0       0
8       0       0
9       10      0
10      0       0
11      -8      0
12      -14     -12
13      0       0
14      0       0
15      0       0
16      0       0
17      -12     -12
Nick
  • 1
  • 1
  • Depends on which version of SQL you are using. You can look at the `LEAD` and `LAG` functions in sql in order to do this. Google Running totals mssql. Look at this https://stackoverflow.com/questions/860966/calculate-a-running-total-in-sql-server – Jaques May 13 '19 at 13:52
  • @Jaques: Ok I will check. Thanks – Nick May 13 '19 at 13:54

0 Answers0