Count values based on conditions and display the result in different columns with MySQL?



Let us first create a table −

mysql> create table DemoTable1485     -> (     -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,     -> StudentName varchar(20),     -> StudentSubject varchar(20)     -> ); Query OK, 0 rows affected (0.72 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','MySQL'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','Java'); Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1485;

This will produce the following output −

+-----------+-------------+----------------+ | StudentId | StudentName | StudentSubject | +-----------+-------------+----------------+ |         1 | Chris       | MySQL          | |         2 | Robert      | MongoDB        | |         3 | Robert      | MongoDB        | |         4 | Chris       | Java           | +-----------+-------------+----------------+ 4 rows in set (0.00 sec)

Here is the query to count values based on conditions −

mysql> select StudentSubject,     -> sum(case when StudentName = 'Chris' THEN 1 ELSE 0 END) Chris_Count,     -> sum(case when StudentName = 'Robert' THEN 1 ELSE 0 END) Robert_Count     -> from DemoTable1485     -> group by StudentSubject;

This will produce the following output −

+----------------+-------------+--------------+ | StudentSubject | Chris_Count | Robert_Count | +----------------+-------------+--------------+ | MySQL          | 1 |           0 | | MongoDB        | 0 |           2 | | Java           | 1 |           0 | +----------------+-------------+--------------+ 3 rows in set (0.00 sec)
Updated on: 2019-11-05T07:15:06+05:30

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements