All problems

The Whale Watch

easySQLSorting

Loopwire has three customer-success managers and far more customers than that, so dedicated attention goes to the largest contracts by monthly billing. The manager building this week's rota wants the three biggest contracts on file, with enough on each line to look the customer up: which account it belongs to, which tier it is, and what it bills. Several contracts bill the same amount as each other, so which of them lands in third place is a real question, and she needs it settled the same way every week rather than however the database feels.

subscriptions — one row per contract. account_id points at a row in accounts. plan is the tier the customer bought. mrr is what that contract bills every month, in dollars. start_date is the day it began. A contract that has stopped carries the day it stopped in end_date; one that is still running has nothing there, shown as below and stored as NULL.

id account_id plan mrr start_date end_date
1 1 starter 49 2022-11-03 2023-02-03
2 1 growth 149 2023-02-03
3 2 growth 149 2022-12-15 2023-06-15
4 3 starter 49 2023-01-31
5 4 growth 149 2023-02-06
6 5 enterprise 499 2023-02-22
7 6 starter 49 2023-03-01 2023-04-01
8 7 growth 149 2023-03-22
9 8 enterprise 499 2023-04-28
10 2 starter 49 2023-06-15

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

Task: Write a query that returns exactly three rows, with columns account_id, plan and mrr — the three contracts with the highest monthly billing. Highest first; two contracts billing the same amount are listed with the smaller account_id first. Cancelled contracts are eligible too.

Example output

Shape only — these accounts and figures are invented; the tier names are the real ones:

account_id plan mrr
12 enterprise 900
19 enterprise 900
27 growth 260

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…