IntermediateJOINs (INNER, LEFT, RIGHT, FULL)

Find top customer per country using JOIN

The query

SQL
SELECT
  c.country,
  c.name AS top_customer,
  country_totals.total_spent
FROM customers c
JOIN (
  SELECT
    cust_id,
    SUM(total) AS total_spent,
    RANK() OVER (PARTITION BY cu2.country ORDER BY SUM(o2.total) DESC) AS rnk
  FROM orders o2
  JOIN customers cu2 ON o2.cust_id = cu2.cust_id
  GROUP BY o2.cust_id, cu2.country
) country_totals ON c.cust_id = country_totals.cust_id
WHERE country_totals.rnk = 1;
Tested against PostgreSQL 16

Note

Derived table (subquery in FROM) joined with main table for per-group top record.

Tables referenced