All problems

What Did This Customer's Balance Look Like Over Time?

hardSQLWindow FunctionsCumulative

A Northline Bank customer has phoned support insisting the balance on their statement is wrong. Support cannot see a balance anywhere — the bank stores movements, not balances — so to answer the call they need to rebuild the account from its transactions and show what it stood at after each one.

The customer in question is customer 1. Their money moved three times: a deposit, a withdrawal, and a transfer out. All three count towards the balance; a transfer leaving the account reduces it exactly as a withdrawal does, and the amounts are already signed so that outgoing money is negative. The table also holds eleven other rows belonging to four other customers, and letting any of those into the calculation produces a balance that belongs to nobody.

transactions — one row per money movement. amount is signed: positive for money in, negative for money out. type is one of deposit, withdrawal or transfer.

id customer_id amount type txn_date
1 1 500 deposit 2023-07-01
2 1 -120 withdrawal 2023-07-03
3 2 1000 deposit 2023-07-02
4 2 -300 withdrawal 2023-07-05
5 3 250 deposit 2023-07-04
6 3 -600 withdrawal 2023-07-06
7 4 800 deposit 2023-07-07
8 4 -450 withdrawal 2023-07-08
9 5 2000 deposit 2023-07-09
10 5 -1500 withdrawal 2023-07-10
11 1 -200 transfer 2023-07-11
12 3 400 deposit 2023-07-12

The table already exists in the database — there is nothing to create or load.

Task: Write a query returning two columns, id and running_balance, covering only customer 1's transactions. running_balance is what the account stood at immediately after that transaction: the amounts of that transaction and every earlier one of theirs added together, taken from oldest date to newest. All three transaction types count. Three rows come back, sorted by id, smallest first.

Example output — shape only, on an invented account. The ids need not be consecutive: only that customer's own rows come back.

id running_balance
4 750
9 300
13 1100

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…