SQL Multiple CTEs
Multiple CTEs sit in one WITH as a list of named results. The names are split by commas, and a later name can read an earlier one.
Spending per customer
Seven totals come back, one per customer. Ben Carter leads at 99.98, ahead of Eli Ross at 84.49.
WITH customer_totals AS (SELECT customer_id, ROUND(SUM(p.price * o.quantity), 2) AS total_spent FROM orders o JOIN products p ON o.product_id = p.product_id GROUP BY customer_id)
SELECT c.name, t.total_spent FROM customer_totals t
JOIN customers c ON t.customer_id = c.customer_id
ORDER BY t.total_spent DESC;The average of those totals
One number comes back: 45.6, the average of the seven customer totals.
WITH customer_totals AS (SELECT customer_id, ROUND(SUM(p.price * o.quantity), 2) AS total_spent FROM orders o JOIN products p ON o.product_id = p.product_id GROUP BY customer_id),
average_total AS (SELECT AVG(total_spent) AS average_spent FROM customer_totals)
SELECT average_spent FROM average_total;Customers above the average
Two customers pass: Ben Carter at 99.98 and Eli Ross at 84.49.
WITH customer_totals AS (SELECT customer_id, ROUND(SUM(p.price * o.quantity), 2) AS total_spent FROM orders o JOIN products p ON o.product_id = p.product_id GROUP BY customer_id),
average_total AS (SELECT AVG(total_spent) AS average_spent FROM customer_totals)
SELECT c.name, t.total_spent FROM customer_totals t
JOIN customers c ON t.customer_id = c.customer_id
WHERE t.total_spent > (SELECT average_spent FROM average_total)
ORDER BY t.total_spent DESC;Example
WITH customer_totals AS (SELECT customer_id, ROUND(SUM(p.price * o.quantity), 2) AS total_spent FROM orders o JOIN products p ON o.product_id = p.product_id GROUP BY customer_id),
average_total AS (SELECT AVG(total_spent) AS average_spent FROM customer_totals)
SELECT c.name, t.total_spent, (SELECT average_spent FROM average_total) AS average_spent FROM customer_totals t
JOIN customers c ON t.customer_id = c.customer_id
WHERE t.total_spent > (SELECT average_spent FROM average_total)
ORDER BY t.total_spent DESC;Key points
- Comma: the mark that splits one named result from the next
- A later CTE can read the rows of an earlier CTE.
- The main query sits after the last CTE in the list.
- Each CTE keeps one job, so a long question splits into short steps.
- The second CTE in this lesson reads the first one, not the tables.
In this example, the first CTE totals each customer's orders. The second CTE averages those totals, which comes to 45.6. The main query lists the two customers above that mark, Ben Carter at 99.98 and Eli Ross at 84.49.
Try it Yourself
Edit the code, then press Run.
Running is simulated · DB Fiddle
Exercise
How can the second CTE in one WITH use the first CTE?