The Net Flow Statement
Northline Bank wants each customer's net flow for the month — the money that arrived minus the money that left, so a positive figure means the account grew and a negative one means it shrank. Because the ledger already records direction in the sign of the amount, this is far less work than it sounds, which is the point of storing it that way.
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 two columns, customer_id and net_flow, one row per customer with at least one movement, net_flow being their money in minus their money out, rounded to 2 decimal places. Largest net flow first; two customers on the same figure come back with the smaller customer_id first.
Example output — shape only, on invented customers. A customer who took out more than they put in shows a negative net_flow, and those sort to the bottom:
| customer_id | net_flow |
|---|---|
| 11 | 9400 |
| 12 | 6250 |
| 13 | -3100 |
| 14 | -5800 |
| 15 | -7700 |
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