Summarising a summary
A subquery can also sit in FROM, where it acts like a table you've made on the spot. This is the
way to summarise a summary: first total things up, then work on the totals.
How many orders does a typical customer place? First count orders per customer, then average the counts:
SELECT AVG(order_count) AS avg_orders
FROM (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) AS per_customerYou can't write AVG(COUNT(*)): SQL won't put one aggregate straight inside another. The
subquery gets around that.
Give a subquery in FROM a name (AS per_customer). You can join it to other tables, too, like
any table.