0

Say I've a table of Date, Val. Now, I want to maintain a rolling balance where Val gets added to the previous row to give X, which then gets added to the next row and thus it continues to give rise to a column that has the rolling balance. So on any date I query, I can get the current balance.

Using window functions, I can always add the current row with the previous row, but I'm not able to figure how to carry over that value to the next row's summation.

RandomGuy
  • 343
  • 3
  • 10

1 Answers1

0

Window functions does the job you asked. Please look for "order by" clause of WF:

select sum(Val) over (order by Date) 

sliding window from unbound preceding to current row is default for order by, to make a task of cumulative summing easy.

See expanded answer here - Calculating Cumulative Sum in PostgreSQL