Sub topic 2
Grouping by more than one column
This chapter assumes you know basic SELECT, FROM, WHERE and ORDER BY syntax, that NULL means a missing value, and that you have seen GROUP BY with a single column. The examples use an orders table with the columns order_id, customer_id, status, amount and shipped_at.
Grouping by more than one column
A GROUP BY clause with several columns creates one group for each distinct combination of those values. Rows with the same customer_id and the same status land in the same group.
SELECT customer_id,
status,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id, status;Each output row describes one customer's orders in one status. Adding a column to GROUP BY usually produces more rows, because it splits existing groups into smaller ones.
What a grouped query may select
After grouping, each output row represents a group, not a single source row. A column in the SELECT list must therefore be either listed in GROUP BY or wrapped in an aggregate function such as COUNT, SUM, AVG, MIN or MAX.
customer_idandstatusare allowed because they appear inGROUP BY.SUM(amount)is allowed because it is an aggregate.- A bare
amountis not allowed, because one group contains several amounts and the database cannot choose one.
The logical order of query evaluation
The database does not run a query in the order you write it. It evaluates the clauses in this logical order:
Because SELECT runs after GROUP BY, aliases defined in SELECT cannot be used in WHERE or HAVING. The ORDER BY clause runs last, so it may use aliases.
Filtering rows with WHERE and groups with HAVING
WHERE filters individual rows before grouping. HAVING filters groups after aggregation, so it can refer to aggregate values.
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) > 1000;This query first discards unpaid orders, then totals the paid amount per customer, then keeps only customers whose total exceeds 1000.
Exercise
Which clause should hold the condition "only orders with status 'paid'": WHERE or HAVING? Write a query that also keeps only customers with more than 3 paid orders.
Show answer
The status test goes in WHERE because it checks a row column. The count test goes in HAVING because it checks an aggregate: SELECT customerid, COUNT(*) AS paidorders FROM orders WHERE status = 'paid' GROUP BY customer_id HAVING COUNT(*) > 3;