Intermediate
Case 28 of 50
Case 028: The High-Value Customers
customersorderspayments
ByteMart's queries are getting complex enough that Alex starts naming intermediate steps instead of nesting subqueries. The manager is back with a follow-up.
"Same question as before — who's spent over $20,000 — but I'll need this report every week, so could you make it something we can actually read back later?"
The data Alex is looking at
customers
| id | name | country | signup_date |
|---|---|---|---|
| 1 | Sam | Germany | 2026-01-02 |
| 2 | Nina | Canada | 2026-01-05 |
| 3 | David | Germany | 2026-01-10 |
| 4 | Maya | Japan | 2026-01-15 |
| 5 | Daniel | Canada | 2026-01-20 |
| … 5 more rows | |||
orders
| id | customer_id | order_date |
|---|---|---|
| 101 | 1 | 2026-01-05 |
| 102 | 2 | 2026-01-08 |
| 103 | 3 | 2026-01-12 |
| 104 | 1 | 2026-01-20 |
| 105 | 4 | 2026-02-01 |
| … 23 more rows | ||
payments
| id | order_id | amount |
|---|---|---|
| 601 | 101 | 6200 |
| 602 | 102 | 3500 |
| 603 | 103 | 3600 |
| 604 | 104 | 60000 |
| 605 | 105 | 12000 |
| … 23 more rows | ||
TASK
Help Alex answer the manager:
“Using a CTE, display each customer’s name and total spending for customers who spent more than $20,000.”
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
orders.customer_id,
SUM(payments.amount) AS total
FROM orders
JOIN payments ON payments.order_id = orders.id
GROUP BY orders.customer_id
)
SELECT
customers.name,
customer_totals.total
FROM customer_totals
JOIN customers ON customers.id = customer_totals.customer_id
WHERE customer_totals.total > 20000
ORDER BY customer_totals.total DESC;
What that query returns
Case Debrief
CTE (WITH clause)
- CTE stands for Common Table Expression. WITH name AS (...) defines a named, reusable result set for the rest of the query — the same power as a subquery, but far more readable once queries get complex.