← SQL Deep Dive
14 / 25
Lesson 14 — CASE inside aggregates (pivot)
CASE inside aggregates: a pivot table
Put CASE inside SUM or COUNT to count only certain rows per group. This turns rows into columns — a pivot. SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) adds only paid amounts.
SELECT month,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid
FROM invoices GROUP BY month
Why it matters: "paid vs unpaid per month" side by side in one row is exactly what managers want in a spreadsheet.
Want it another way?
Task
Fill in the unpaid column the same way as paid. Expected: ('Jan', 150.0, 40.0) and ('Feb', 60.0, 90.0).
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.