Practice 2: Top 3 Customers per Region
Marketing is looking for VIP upgrade candidates: "Among NORMAL-grade customers, pick the three who bought the most in Q1 2024 in each region."
Requirements
- Only customers whose grade is
NORMAL. - Only Q1 2024 orders:
ord_nofrom20240101(inclusive) to20240401(exclusive). - Leave out canceled orders (
status = 'CANCELED') and sum the rest of the amounts per customer. - In each region (
region), rank 1, 2, 3 by the total, largest first. On equal totals the smallercust_idcomes first. No ties: each rank is given once.
Result format
| Column | Meaning |
|---|---|
region | Region |
rnk | Rank in the region (1-3) |
cust_id | Customer number |
cust_nm | Customer name |
total_amt | Q1 total amount |
Sort by region, then rnk. There are 5 regions, so the result has 15 rows.
My solution
My solution
SELECT c.region, c.cust_id, c.cust_nm, SUM(o.amt) AS total_amt
FROM customers c
JOIN orders o ON o.cust_id = c.cust_id
WHERE c.grade = 'NORMAL'
AND o.ord_no >= '20240101' AND o.ord_no < '20240401'
GROUP BY c.region, c.cust_id, c.cust_nm
ORDER BY total_amt DESC
Hints
- A ranking window function cannot be used in
WHERE. Splitting it into two WITH steps — total per customer, then rank, then filter — keeps it readable (WITH patterns, Group-wise maximum). - "No ties, each rank once" means
ROW_NUMBER, notRANK. Put the tie-breaker in theORDER BYtoo, so the result is determined.