Sub topic 3
Grouping by Expressions such as CASE
This chapter assumes you know SELECT, WHERE, JOIN, GROUP BY, and the five aggregates (COUNT, SUM, AVG, MIN, MAX). You should also understand that NULL means a missing value.
Grouping by an expression
GROUP BY accepts any expression, not only a column name. Each distinct result of the expression forms one group.
SELECT CASE WHEN amount >= 100 THEN 'large' ELSE 'small' END AS size_band,
COUNT(*) AS order_count
FROM orders
GROUP BY CASE WHEN amount >= 100 THEN 'large' ELSE 'small' END;Conditional aggregation
Put a CASE inside an aggregate to sum only matching rows. This produces one column per category in a single pass, a pivot-style summary.
SELECT customer_id,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_total,
SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END) AS refunded_total
FROM orders
GROUP BY customer_id;Aggregating across joins
A join that matches one order to several payments repeats the order's amount once per payment. SUM then counts it twice. Aggregate the detail table first, then join the result.
SELECT c.customer_id, o.total
FROM customers AS c
JOIN (SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id) AS o
ON o.customer_id = c.customer_id;Subtotals with ROLLUP
ROLLUP adds subtotal rows and a grand total row. Rolled-up columns contain NULL in those rows. Use GROUPING(column) to tell a subtotal NULL from a real NULL.
SELECT customer_id, status, SUM(amount) AS total_amount
FROM orders
GROUP BY ROLLUP (customer_id, status);CUBE produces every combination of the listed columns. GROUPING SETS lets you list the exact combinations you want.
When to use a window function
GROUP BY collapses rows. A window function keeps every row and adds the aggregate beside it. Use a window when you need the detail row and the total together.
SELECT order_id, customer_id, amount,
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total
FROM orders;Common mistakes and checks
- Selecting a column that is neither grouped nor aggregated causes an error.
- Filter rows with WHERE before grouping, and filter groups with HAVING after.
- After a join, compare the summed total with the total from the base table.
Exercise
Exercise
Write a query that returns each customerid with paidtotal and refunded_total, using only the orders table.
Show answer
SELECT customerid, SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paidtotal, SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END) AS refundedtotal FROM orders GROUP BY customerid;