There are a ton of questions about calculating running totals with Postgres but I am struggling to do something slightly different.
I have a table that looks like this
txn_id | amount |
---|---|
String | Integer |
amounts
can either be positive or negative.
I am trying to return a table that looks like this
txn_id | amount | running_total | overage_total |
---|---|---|---|
String | Integer | Integer | Integer |
Where running total is running sum of the amount
column as long as the amount is greater than zero and overage_total
is the running sum of amounts that were lower than zero.
An example of would be
txn_id | amount |
---|---|
a | 1 |
b | 2 |
c | -4 |
d | 2 |
e | -1 |
I have been using a window function for the running sum but it's not quite what we need.
The correct table would return
txn_id | amount | running_total | overage_total |
---|---|---|---|
a | 1 | 1 | 0 |
b | 2 | 3 | 0 |
c | -4 | 0 | 1 |
d | 2 | 2 | 1 |
e | -1 | 1 | 1 |
Currently I have am doing this in code but it would be really incredible to do it in the database if it's possible.