-1

I want to create cumulative sum in table ( Commul_table) in SQL such as Z=Z+ (A+B-C )

Commul_table i want compute value of Z

Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
Ali Jamal
  • 3
  • 2

3 Answers3

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
  • 4
  • 8
1

It's still a Cumulative Sum, just based on a calculation on three columns:

sum(a+b-c) over (order by Id rows unbounded preceding)

See fiddle

dnoeth
  • 57,618
  • 3
  • 33
  • 50
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,198,228
  • 53
  • 572
  • 709