Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative sum over a table

What is the best way to perform a cumulative sum over a table in Postgres, in a way that can bring the best performance and flexibility in case more fields / columns are added to the table.

Table

    a   b   d
1   59  15  181
2       16  268
3           219
4           102

Cumulative

    a   b   d
1   59  15  181
2       31  449
3           668
4           770
like image 503
Alg_D Avatar asked Feb 02 '26 05:02

Alg_D


1 Answers

You can use window functions, but you need additional logic to avoid values where there are NULLs:

SELECT id,
       (case when a is not null then sum(a) OVER (ORDER BY id) end) as a,
       (case when b is not null then sum(b) OVER (ORDER BY id) end) as b,
       (case when d is not null then sum(d) OVER (ORDER BY id) end) as d 
FROM table;

This assumes that the first column that specifies the ordering is called id.

like image 116
Gordon Linoff Avatar answered Feb 04 '26 21:02

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!