Subqueries and CTEs · Problem 63 of 118

Customers Above the Average Spender

HardSubqueries and CTEsShop data

A customer's spending is the sum of quantity * unit_price over all lines of their orders that are not cancelled (status <> 'cancelled'), rounded to 2 decimals. The average is taken over customers who have spending (at least one non-cancelled order).

Return customer_id and spent for the five customers with the highest spending that is above that average. Sort by spent from high to low, then customer_id.

Hint 1

Step 1: one row per order line with the customer. Step 2: spending per customer. Step 3: compare with the average of step 2. Name each step with WITH.

Reference solution

WITH per_customer AS (
  SELECT o.customer_id, ROUND(SUM(oi.quantity * oi.unit_price), 2) AS spent
  FROM orders AS o
  JOIN order_items AS oi ON oi.order_id = o.order_id
  WHERE o.status <> 'cancelled'
  GROUP BY o.customer_id
)
SELECT customer_id, spent
FROM per_customer
WHERE spent > (SELECT AVG(spent) FROM per_customer)
ORDER BY spent DESC, customer_id
LIMIT 5;

A WITH clause gives a name to a step, so the query reads from top to bottom like a recipe. Here per_customer is used twice (as the table to read and inside the average), which a plain subquery would force you to write out twice. When a query goes wrong, test each CTE on its own with SELECT * FROM per_customer LIMIT 5 and check the numbers before moving on.