InterviewPrepKit

Home / SQL / Window Functions

Running Balance per Account

medium
Solving tips
  • A running total is SUM(...) OVER (PARTITION BY key ORDER BY time) — the ORDER BY is what turns the sum cumulative.
  • Be explicit with the frame: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW behaves predictably even when the ORDER BY column has duplicate values.
  • PARTITION BY restarts the accumulation for each account, so balances never bleed across accounts.

Each account has a stream of signed transactions (deposits positive, withdrawals negative). Compute the running balance after each transaction, restarting per account.

Schema

CREATE TABLE transactions (
    account  TEXT,
    txn_date DATE,
    amount   NUMERIC
);
accounttxn_dateamount
A2024-01-01100
A2024-01-03-40
B2024-01-02500
A2024-01-05200
B2024-01-06-100
A2024-01-08-60

Task

For each row return account, txn_date, amount, and running_total — the cumulative sum of amount within the account up to and including that transaction, in date order. Order the output by account ascending, then txn_date ascending.

Expected output

accounttxn_dateamountrunning_total
A2024-01-01100100
A2024-01-03-4060
A2024-01-05200260
A2024-01-08-60200
B2024-01-02500500
B2024-01-06-100400
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.