Interview Puzzles · Problem 107 of 118

Top Spender in Each Country

HardInterview PuzzlesShop data

A customer's spending is the sum of quantity * unit_price over lines of their non-cancelled orders, rounded to 2 decimals. For every country, return the country, the customer_id of the customer with the highest spending in that country (ties: the lower customer_id) and their spent. Sort by country.

Hint 1

First spending per customer with the country, then ROW_NUMBER() OVER (PARTITION BY country ORDER BY spent DESC, customer_id).

Reference solution

WITH spending AS (
  SELECT c.country, c.customer_id, ROUND(SUM(oi.quantity * oi.unit_price), 2) AS spent
  FROM customers AS c
  JOIN orders AS o ON o.customer_id = c.customer_id
  JOIN order_items AS oi ON oi.order_id = o.order_id
  WHERE o.status <> 'cancelled'
  GROUP BY c.country, c.customer_id
), ranked AS (
  SELECT country, customer_id, spent,
         ROW_NUMBER() OVER (PARTITION BY country ORDER BY spent DESC, customer_id) AS n
  FROM spending
)
SELECT country, customer_id, spent
FROM ranked
WHERE n = 1
ORDER BY country;

MAX(spent) tells you how much the best customer spent, but not who they are: the other selected columns are not tied to the row that holds the maximum. To get the whole row of the winner, rank the rows inside each group and keep rank 1. This "get the row with the max per group" pattern is the single most reused window-function idiom in analytics SQL.