Perform count with CASE WHEN statement in MySQL?


For this, you can use CASE WHEN statement. Let us first create a table −

mysql> create table DemoTable1910
   (
   FirstName varchar(20),
   Marks int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1910 values('Chris',45);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1910 values('David',85);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1910 values('Chris',55);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1910 values('Chris',98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1910 values('David',98);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1910;

This will produce the following output −

+-----------+-------+
| FirstName | Marks |
+-----------+-------+
| Chris     |    45 |
| David     |    85 |
| Chris     |    55 |
| Chris     |    98 |
| David     |    98 |
+-----------+-------+
5 rows in set (0.00 sec)

Here is the query to count column values efficiently −

mysql> select FirstName,
   sum(case when Marks=45 then 1 else 0 end),
   sum(case when Marks=98 then 1 else 0 end)
   from DemoTable1910
   group by FirstName;

This will produce the following output −

+-----------+-------------------------------------------+-------------------------------------------+
| FirstName | sum(case when Marks=45 then 1 else 0 end) | sum(case when Marks=98 then 1 else 0 end) |
+-----------+-------------------------------------------+-------------------------------------------+
| Chris     |                                        1 |                                          1 |
| David     |                                        0 |                                          1 |
+-----------+-------------------------------------------+-------------------------------------------+
2 rows in set (0.00 sec)

Updated on: 30-Dec-2019

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements