Skip to content
BytePatterns

Running Balance per Account

MediumSQL#window-function#running-total#window-frame~25m

Problem

A table txn(id, account, day, amount) records deposits as positive amounts and withdrawals as negative ones, and an account can have several transactions on the same day. For every transaction, return the account's balance right after it, as columns account, day, amount and balance, sorted by account, then day, then id. Each transaction has to move the balance on its own, one row at a time, even when two of them share a day.

Examples

Input:  txn = [(1, "A", "2026-09-01", 100), (2, "B", "2026-09-01", 50), (3, "A", "2026-09-02", -30), (4, "A", "2026-09-02", 20), (5, "B", "2026-09-03", -50)]
Output: [("A", "2026-09-01", 100, 100), ("A", "2026-09-02", -30, 70), ("A", "2026-09-02", 20, 90),
         ("B", "2026-09-01", 50, 50), ("B", "2026-09-03", -50, 0)]
Why:    A's two transactions on 09-02 give 70 and then 90, not 90 twice
Input:  txn = [(1, "A", "2026-09-01", 40)]
Output: [("A", "2026-09-01", 40, 40)]
Why:    edge case, a single transaction is its own balance

Hints

0 / 3

Stuck on the idea rather than the code? Window Functions covers it.