Overview
Rank the top 3 customers by paid revenue: join, filter, group, keep only regular customers with HAVING, then sort and limit.
- JOIN, WHERE, GROUP BY, HAVING
- ORDER BY then LIMIT
- Filter before you aggregate
Short Course
Real reports chain every clause in a fixed order: JOIN, WHERE,
GROUP BY, HAVING, ORDER BY, LIMIT. Trap: WHERE runs before the
grouping, so a refund filtered in HAVING would already be inside the
totals. Filter rows in WHERE, groups in HAVING.
SELECT c.country, SUM(o.total) AS revenue
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.status = 'paid'
GROUP BY c.country
HAVING COUNT(*) >= 2
ORDER BY revenue DESC
LIMIT 3;
Task
Return the top 3 customers by paid revenue: their name, number of paid
orders and paid revenue, only for customers with at least 2 paid orders,
highest revenue first. In the database below, Bo has the biggest single order
but only one.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | nameTEXT |
|---|---|
| 1 | Ana |
| 2 | Bo |
| 3 | Cy |
| 4 | Di |
| 5 | Eve |
| idINTEGER | customer_idINTEGER | statusTEXT | totalREAL |
|---|---|---|---|
| 1 | 1 | paid | 50.0 |
| 2 | 1 | paid | 70.0 |
| 3 | 2 | paid | 300.0 |
| 4 | 3 | paid | 40.0 |
| 5 | 3 | paid | 45.0 |
| 6 | 3 | refunded | 500.0 |
| 7 | 4 | paid | 60.0 |
| 8 | 4 | paid | 80.0 |
| 9 | 5 | paid | 10.0 |
| 10 | 5 | paid | 15.0 |
Test Suites
Pending
Next
Output