Deviopath › PostgreSQL

Running Balance Goes Negative

Hard · Window Functions

A running total is SUM(amount) OVER (PARTITION BY ... ORDER BY ...): each row gets the sum of all rows up to and including itself.

Each account starts at its opening_balance; transactions are applied in order of posted_on, then id. After every transaction the account has a new balance.

For every account (including accounts with no transactions), return:

- owner

- first_negative_on: the posted_on date of the first transaction after which the balance was below zero, or NULL if it never was (a balance of exactly 0.00 is not negative)

- lowest_balance: the lowest balance the account ever had, counting the opening balance

Next: Median Salary per Department