Sql - Pivot with SUM(CASE)
📖 Read the lesson
Code Life
By Pierre Marsaa
Counting with a condition
Put a
CASE
inside an aggregate
and you can count or add only the rows that match a condition. Each matching row contributes
1
, the others
0
:
↗️
Loading editor...
↶
▶️ Run
↷
Add
GROUP BY
and you get the count per group — here, per type, the number of Codémons that win more than they lose:
↗️
Loading editor...
↶
▶️ Run
↷
COUNT works too
COUNT(CASE WHEN wins > losses THEN
1
END)
gives the same result: without
ELSE
, the other rows become NULL, and
COUNT
ignores NULL.
Verify