Subqueries and CTEs · Problem 66 of 118

Orders Above the Customer's Own Average

HardSubqueries and CTEsShop data

The total of an order is the sum of quantity * unit_price over its lines (cancelled orders included), rounded to 2 decimals. For customers 1 to 5, return customer_id, order_id and total for every order whose total is higher than the average total of that customer's orders. Sort by customer_id, then order_id.

Hint 1

Step 1: a CTE with one row per order (customer and total). Step 2: for each order, compare with the average of the same customer's rows in the CTE.

Reference solution

WITH totals AS (
  SELECT o.customer_id, o.order_id, ROUND(SUM(oi.quantity * oi.unit_price), 2) AS total
  FROM orders AS o
  JOIN order_items AS oi ON oi.order_id = o.order_id
  GROUP BY o.customer_id, o.order_id
)
SELECT t.customer_id, t.order_id, t.total
FROM totals AS t
WHERE t.customer_id BETWEEN 1 AND 5
  AND t.total > (SELECT AVG(t2.total) FROM totals AS t2 WHERE t2.customer_id = t.customer_id)
ORDER BY t.customer_id, t.order_id;

The inner WHERE t2.customer_id = t.customer_id is what makes the subquery correlated: it recomputes the average for each customer. Without it you compare everyone with the global average, which answers a different question. The same result can be written with a window function (AVG(total) OVER (PARTITION BY customer_id)), as you will see in the next chapter.