Count, sum and average per group, filter before and after aggregating — and see why every GROUP BY shuffles.
An aggregate function turns many rows into one value: count, sum, avg, min, max. GROUP BY says per what: you get one output row per distinct value — or combination of values — of the grouping columns. All NULLs in a grouping column land together in one NULL group.
Every column in the SELECT list must be a grouping column or sit inside an aggregate. SELECT customer_id, status, sum(amount) … GROUP BY customer_id fails analysis: Spark can't know which status to show for a customer with ten orders.
SELECT status,
count(*) AS orders,
sum(amount) AS revenue,
avg(amount) AS avg_order
FROM orders
GROUP BY status
ORDER BY revenue DESC;Reach the last step for the run summary: the key takeaways from this lesson.