Sub topic 10
Conditional aggregation for pivot-style summaries
Assume you know SELECT, WHERE, GROUP BY, HAVING, CASE, and basic NULL behavior. This chapter uses an orders table with customer_id, status, and amount.
Turning row values into columns
A grouped query normally returns one row for each group. Conditional aggregation lets you calculate several filtered aggregates in the same row. It combines an aggregate function, such as SUM or COUNT, with a CASE expression.
For example, suppose status can be paid, refunded, or pending. You can create one total column for each status:
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,
SUM(CASE WHEN status = 'pending'
THEN amount ELSE 0 END) AS pending_total
FROM orders
GROUP BY customer_id;Each CASE returns the amount for matching rows. It returns zero for other rows. SUM then adds the values within each customer group.
The result has a pivot-style shape:
| customer_id | paid_total | refunded_total | pending_total |
|---|---|---|---|
| 101 | 250.00 | 20.00 | 75.00 |
A pivot-style summary changes values found in rows into separate summary columns. Unlike a database-specific PIVOT command, conditional aggregation works in many SQL systems.
Choosing `ELSE 0` or `ELSE NULL`
SUM ignores NULL. Therefore, these two expressions usually produce the same total when at least one row matches:
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END)
SUM(CASE WHEN status = 'paid' THEN amount END)They differ when no row matches. The first expression returns 0. The second returns NULL. Use ELSE 0 when “no matching amount” should mean zero. Keep NULL when you need to distinguish “no matching rows” from a real total of zero.
The source amount can also be NULL. Both SUM versions ignore a matching row whose amount is NULL. If every matching amount is NULL, SUM returns NULL, unless you handle it with COALESCE:
COALESCE(
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END),
0
) AS paid_totalCounting conditions
Use COUNT when you need quantities instead of money. A common pattern is to return a non-NULL value for matches and NULL otherwise:
SELECT customer_id,
COUNT(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
COUNT(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders
FROM orders
GROUP BY customer_id;COUNT(expression) counts only non-NULL results. Thus, the first expression counts paid orders and skips every other status.
Some systems support FILTER, which expresses the condition separately:
SELECT customer_id,
COUNT(*) FILTER (WHERE status = 'paid') AS paid_orders,
SUM(amount) FILTER (WHERE status = 'paid') AS paid_total
FROM orders
GROUP BY customer_id;CASE is often more portable. Check your database documentation before using FILTER.
Avoiding overlapping conditions
Conditions should usually describe separate categories. If conditions overlap, one row can contribute to multiple columns:
SUM(CASE WHEN amount >= 100 THEN amount ELSE 0 END) AS large_total,
SUM(CASE WHEN amount >= 500 THEN amount ELSE 0 END) AS very_large_totalOrders of 500 or more appear in both totals. That is correct only if the overlap is intentional. For mutually exclusive categories, use ranges:
SUM(CASE WHEN amount < 100 THEN amount ELSE 0 END) AS small_total,
SUM(CASE WHEN amount >= 100 AND amount < 500 THEN amount ELSE 0 END) AS medium_total,
SUM(CASE WHEN amount >= 500 THEN amount ELSE 0 END) AS large_totalExercise
Write a grouped query that returns each customer’s number of paid orders and total amount from paid orders.
Show answer
SELECT customerid, COUNT(CASE WHEN status = 'paid' THEN 1 END) AS paidorders, SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paidtotal FROM orders GROUP BY customerid;