Excellent job! Another situation where nested CTEs can be useful is comparing two groups of items. Check it out:
WITH grouping AS (
id AS city_id,
CASE WHEN region = 'Europe' THEN region ELSE 'Other' END AS group_name
total_salesman_earnings AS (
SUM(amount_earned) AS total_amount
FROM daily_sales d
JOIN salesman s
ON d.salesman_id = s.id
JOIN grouping g
ON g.city_id = s.city_id
GROUP BY salesman_id, group_name
FROM total_salesman_earnings s
GROUP BY group_name
We want to compare the average earnings of salespeople from Europe with those from other parts of the world.
In the first CTE, we define the groups: cities from Europe are labeled
'Europe', while cities outside Europe are labeled
'Other'. In the second CTE, we compute the total amount earned for each salesperson and combine this information with the group definition (i.e.
'Other') for that salesperson.
In the outer query, we compute the group-level average.