Pivot with CASE
- SQL course
- Advanced
- Lesson 25/81
- 4 min
Pivot using CASE and aggregates.
Pivot with CASE
You pivot with CASE and SUM. Each category becomes a column.
SELECT
SUM(CASE WHEN category = 'Kitap' THEN amount ELSE 0 END) AS Kitap,
SUM(CASE WHEN category = 'Elektronik' THEN amount ELSE 0 END) AS Elektronik
FROM sales;Two columns for two categories.
SUM(CASE WHEN category = 'Kitap' THEN amount ELSE 0 END) … is selected from sales.
Pivot with CASE — details
CASE produces values per category, SUM aggregates them. Each category is a separate column.
Writing ELSE 0 for non-matching rows matters; without ELSE the CASE returns NULL, and while SUM still works, functions like COUNT can give wrong results.
Practice Pivot with CASE
Produce a Book column with SUM(CASE WHEN category = 'Kitap' THEN amount ELSE 0 END).
Starter code
-- pivot with case
SELECT
SUM(Sample solution
SELECT
SUM(CASE WHEN category = 'Kitap' THEN amount ELSE 0 END) AS Kitap,
SUM(CASE WHEN category = 'Elektronik' THEN amount ELSE 0 END) AS Elektronik
FROM sales;Expected output
Kitap 200
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add SUM
SELECT
____(CASE WHEN category = 'Kitap' THEN amount ELSE 0 END) AS Kitap
FROM sales;
SELECT
SUM(CASE WHEN category = 'Kitap' THEN amount ELSE 0 END) AS Kitap
FROM sales;
Explanation: CASE returns the amount only for matching rows and 0 otherwise; SUM adds them up into a column.
2 What is summed in a CASE pivot?
- The CASE result Correct answer
- All rows
- An index
- The column name
Explanation: The CASE result is summed with SUM.
3 Pivot with CASE: match the terms
| Term | Meaning |
|---|---|
CASE |
condition |
SUM |
sum |
category |
column |
pivot |
convert |