First, this was my first question concerning that issue : SQL request to group and sum numbers by their day of creation
Now, imagine I want to make it more complex, after previous operations and thanks to answers, I have results grouped by day, so each entries of the day are added. I have this :
1 | 200 | 2010-01-01
2 | 100 | 2010-01-01
Transformed into this :
1 | 300 | 2010-01-01
That’s already pretty good, but what if I want the amount field to increment each time ?
1 | 300 | 2010-01-01
2 | 200 | 2010-01-02
Will become :
1 | 300 | 2010-01-01
2 | 500 | 2010-01-02
x | (previous amount + this amount) | this date
The sql query I got thanks to answers to my previous question :
select sum(amount), to_char(date, 'YYYY-MM-DD')
from mytable
group by to_char(date, 'YYYY-MM-DD')
order by sum(amount) ASC;
A running sum can be done using windowing functions:
If you want the running sum over the aggregated result, just put it into a sub-query:
If the column
dateis actual of the data typedate, then there is no reason to use to_char() on it. Btw: it’s not a terribly good idea to use reserved words (date) for column names.The important thing here is the
order byas part of theoverdefinition.More details in the manual: http://www.postgresql.org/docs/current/static/tutorial-window.html