I want to create cumulative sum in table ( Commul_table) in SQL such as Z=Z+ (A+B-C )
Asked
Active
Viewed 163 times
-1
-
Does this answer your question? https://stackoverflow.com/questions/2120544/how-to-get-cumulative-sum – Ziba Aug 20 '20 at 20:34
-
no , because i want to add and subtract more than one cell in each row in column Z , (Z=Z+A+B-C) – Ali Jamal Aug 20 '20 at 20:40
-
`sum(a+b-c) over (order by Id rows unbounded preceding)` – dnoeth Aug 20 '20 at 21:11
-
The sample data seems to have nothing to do with the calculations you are suggesting. The second `z` value should be 8. – Gordon Linoff Aug 20 '20 at 21:44
3 Answers
2
You can use analytic function
in this case with rows unbounded preceding
(to get sum values before current row)
Select id, A,B,C,sum(A+B-C) over(order by Id rows unbounded preceding) as Z
From Table

Olga Romantsova
- 1,096
- 1
- 6
- 8
1
I'm answering to point out that the window frame clause is not needed in most databases. Assuming that the id
is unique:
select ct.*, sum(a + b - c) over (order by id) as z
from Commul_table;
If id
can be duplicated, please explain what you want for the results. The above also assumes that a
, b
, and c
are never NULL
. If they can be, then you want to substitute 0
for them:
select ct.*,
sum(coalesce(a, 0) + coalesce(b, 0) - coalesce(c, 0)) over (order by id) as z
from Commul_table;

Gordon Linoff
- 1,242,037
- 58
- 646
- 786