I have a table where I want to get the first record after a certain value is reached with sum. I'm using PostgreSQL 9.3.
So – for the following table, summing the amount column for a specific user (eg user 1) I want the record where the amount gets to zero or below, in this case record with deposit_id 8.
deposit_id | user_id | amount
-----------------------------------------------------------
1 | 1 | +10
2 | 1 | +5
3 | 2 | +10
4 | 1 | +5
5 | 2 | +5
6 | 1 | -15
7 | 1 | -3
8 | 1 | -3
9 | 1 | -5
What would the best way to structure a query for a specific user to sum the values and stop when the value has reached 0 or below and return the record which pushed it over the edge (the first record where total sum of amounts <= 0)?
Best Answer
A cumulative sum can be reached with a Window function and a CTE, the difficult part is to stop it.
To get the first element where total <= 0
dbfiddle here