How can column data be used within MySQL CASE statement?


To understand it consider the data, as follows, from the table ‘Students’ −

mysql> Select * from Students;
+----+-----------+-----------+----------+----------------+
| id | Name      | Country   | Language | Course         |
+----+-----------+-----------+----------+----------------+
| 1  | Francis   | UK        | English  | Literature     |
| 2  | Rick      | USA       | English  | History        |
| 3  | Correy    | USA       | English  | Computers      |
| 4  | Shane     | France    | French   | Computers      |
| 5  | Validimir | Russia    | Russian  | Computers      |
| 6  | Steve     | Australia | English  | Geoinformatics |
| 7  | Rahul     | India     | Hindi    | Yoga           |
| 8  | Harshit   | India     | Hindi    | Computers      |
| 9  | Harry     | NZ        | English  | Electronics    |
+----+-----------+-----------+----------+----------------+
9 rows in set (0.00 sec)

Now, suppose if we want to know that how many of the students belong to USA, UK, NZ, INDIA, RUSSIA, FRANCE and so on then we can use column ‘country’ within CASE statement as follows −

mysql> Select SUM(CASE WHEN country = 'USA' THEN 1 ELSE 0 END) AS USA,
-> SUM(CASE WHEN country = 'UK' THEN 1 ELSE 0 END) AS UK,
-> SUM(CASE WHEN country = 'INDIA' THEN 1 ELSE 0 END) AS INDIA,
-> SUM(CASE WHEN country = 'Russia' THEN 1 ELSE 0 END) AS Russia,
-> SUM(CASE WHEN country = 'France' THEN 1 ELSE 0 END) AS France,
-> SUM(CASE WHEN country = 'NZ' THEN 1 ELSE 0 END) AS NZ,
-> SUM(CASE WHEN country = 'Australia' THEN 1 ELSE 0 END) AS Australia
-> From Students;
+------+------+-------+--------+--------+------+-----------+
| USA  | UK   | INDIA | Russia | France | NZ   | Australia |
+------+------+-------+--------+--------+------+-----------+
| 2    | 1    | 2     | 1      | 1      | 1    | 1         |
+------+------+-------+--------+--------+------+-----------+
1 row in set (0.07 sec)

Rishi Raj
Rishi Raj

I am a coder

Updated on: 20-Jun-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements