All problems

The Running Balance

hardSQLWindow FunctionsCASE

A Northline Bank customer has queried their statement, and support needs to reconstruct what the balance read after each of customer 1's movements — the running balance, meaning the total of everything up to and including that line. Only customer 1's rows belong on the statement.

transactions — one row per movement of money. customer_id points at a row in customers; type is one of deposit, withdrawal or transfer; txn_date is the day it settled. The ledger is signed: money arriving in an account is stored as a positive amount, and money leaving it as a negative one, so a 600-dollar withdrawal is recorded as -600.

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 that returns three columns — txn_date, type and balance — one row per movement belonging to customer 1, in date order from earliest to latest, with id breaking any same-day tie. balance is the total of that customer's amounts up to and including the row it sits on, rounded to 2 decimal places, starting from zero before the first movement.

Example output — shape only, on invented movements. Each balance carries the ones above it along with the row it sits on, so the column rises and falls as the customer pays in and takes out:

txn_date type balance
2019-03-04 deposit 900
2019-03-12 withdrawal 640
2019-03-27 transfer 210

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…