Advanced Case 39 of 50

Case 039: Spending Quartiles

customersorderspayments

The manager wants to split the customer base into four equal-sized tiers for a targeting campaign.

"Rather than exact ranks, could you just tell me which quartile each customer falls into?"

The data Alex is looking at

customers
idnamecountrysignup_date
1SamGermany2026-01-02
2NinaCanada2026-01-05
3DavidGermany2026-01-10
4MayaJapan2026-01-15
5DanielCanada2026-01-20
… 5 more rows
orders
idcustomer_idorder_date
10112026-01-05
10222026-01-08
10332026-01-12
10412026-01-20
10542026-02-01
… 23 more rows
payments
idorder_idamount
6011016200
6021023500
6031033600
60410460000
60510512000
… 23 more rows
TASK

Help Alex answer the manager:

“Split customers into four equal-sized groups (quartiles) based on total spending, showing their total and which quartile they fall into — highest spenders in quartile 1.”
SQL editor Ctrl+Enter to run
Write a query above and hit Run to see what comes back.
No hints requested yet — click "Get a hint" when you're stuck.
Alex's final query — this is for reference. Copy it into your own thinking, not into the editor above.
WITH customer_totals AS ( SELECT customers.name, SUM(payments.amount) AS total FROM customers JOIN orders ON customers.id = orders.customer_id JOIN payments ON payments.order_id = orders.id GROUP BY customers.name ) SELECT name, total, NTILE(4) OVER (ORDER BY total DESC) AS spending_quartile FROM customer_totals;
What that query returns
Case Debrief NTILE()
  • NTILE(n) buckets ordered rows into n equal-sized groups — quartiles are NTILE(4), deciles are NTILE(10) (tenths instead of quarters), and any other n works the same way for any "split into tiers" question.

Case closed.

Ready for the next one?

Next: Case 040 — The Rolling Average →