Window Functions · Problem 73 of 118

Running Balance

MediumWindow FunctionsBank data

For account 254, return txn_id and balance_cents: the running balance after each transaction, in the order of txn_date, then txn_id. Money in (deposit, interest, transfer_in) adds to the balance; money out (withdrawal, fee, transfer_out) subtracts. Sort by txn_date, then txn_id.

Hint 1

Make a signed amount with CASE, then add it up: SUM(signed) OVER (ORDER BY txn_date, txn_id).

Reference solution

SELECT txn_id,
       SUM(CASE WHEN kind IN ('deposit', 'interest', 'transfer_in') THEN amount_cents ELSE -amount_cents END)
         OVER (ORDER BY txn_date, txn_id) AS balance_cents
FROM transactions
WHERE account_id = 254
ORDER BY txn_date, txn_id;

SUM(x) OVER (ORDER BY ...) is a running total: each row shows the sum of all rows up to and including itself. The ORDER BY inside OVER defines "up to": include a tie-breaker (txn_id) so rows on the same date are added in a fixed order, otherwise equal dates are treated as one group and share the same running value. The result equals the stored balance_after column of this data, which is exactly how an accountant would reconcile it.