All problems

Whose Balance Grew the Least?

mediumSQLGroupBySorting

Relationship managers at Northline Bank make a handful of check-in calls each cycle, and the one they most want to make is to the customer whose balance moved least in their favour — often the first sign that the money is going somewhere else.

The ledger makes this a small piece of arithmetic rather than a lookup. There is no balance column: there are only individual movements, and the sign is already carried on the amount, so money leaving is stored as a negative number. A customer's position for the cycle is what all their movements come to when taken together, and no row holds that figure.

transactions — one row per movement of money. amount is in dollars and is negative when money leaves the account. type says what kind of movement it was.

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 a single row with two columns, customer_id and net_change, for the customer whose movements come to the smallest total for the cycle. Every movement counts, of every type, and the signs in the data are already correct — nothing needs flipping. Exactly one row comes back. No two Northline customers tie on this data, so there is no tie to settle.

Example output — shape only, on an invented customer; a cycle that ended down on the month comes back negative.

customer_id net_change
8 -125

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…