I learnt that the difference between CASE and IF statement is as follows "IF is a CASE with only one 'WHEN' statement". But I got confused when querying this:
I have the table Olympics which contains the countries and medals associated to it. I am counting the total number of medals won by each country. The first query results in the correct output but second query does not. Can anyone tell the reason why case-when and if statement are working differently here?
First query
select
NOC,
COUNT(IF (medal = "GOLD", medal, NULL)) as GOLD,
COUNT(IF (medal = "SILVER", medal, NULL)) as SILVER,
COUNT(IF (medal = "BRONZE", medal, NULL)) as BRONZE
from olympics
group by NOC;
| NOC | GOLD | SILVER | BRONZE |
|---|---|---|---|
| ARG | 1 | 0 | 0 |
| ARM | 0 | 2 | 0 |
| AUS | 1 | 1 | 1 |
Second query
select NOC,
count(case when MEDAL='GOLD' then '1' ELSE 0 end) as GOLD,
count(case when MEDAL='SILVER' then '1' ELSE 0 end) as SILVER,
count(case when MEDAL='BRONZE' then '1' ELSE 0 end) as BRONZE
from olympics
group by NOC
| NOC | GOLD | SILVER | BRONZE |
|---|---|---|---|
| ARG | 1 | 1 | 1 |
| ARM | 2 | 2 | 2 |
| AUS | 3 | 3 | 3 |