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_no from 20240101 (inclusive) to 20240401 (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 smaller cust_id comes first. No ties: each rank is given once.

Result format

ColumnMeaning
regionRegion
rnkRank in the region (1-3)
cust_idCustomer number
cust_nmCustomer name
total_amtQ1 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, not RANK. Put the tie-breaker in the ORDER BY too, so the result is determined.