Count multiple rows and display the result in different columns (and a single row) with MySQL


Let us first create a table −

mysql> create table DemoTable1452
   -> (
   -> FavouriteColor varchar(50)
   -> );
Query OK, 0 rows affected (2.42 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1452 values('Red');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable1452 values('Yellow');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1452 values('Yellow');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1452 values('Yellow');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1452 values('Blue');
Query OK, 1 row affected (0.42 sec)
mysql> insert into DemoTable1452 values('Blue');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable1452 values('Red');
Query OK, 1 row affected (0.29 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1452;

This will produce the following output −

+----------------+
| FavouriteColor |
+----------------+
| Red            |
| Yellow         |
| Yellow         |
| Yellow         |
| Blue           |
| Blue           |
| Red            |
+----------------+
7 rows in set (0.00 sec)

Following is the query to count multiple rows and display the result in different columns −

mysql> select sum(FavouriteColor='Red') as NumberOfRedColor,
   -> sum(FavouriteColor='Yellow') as NumberOfYellowColor,
   -> sum(FavouriteColor='Blue') as NumberOfBlueColor
   -> from DemoTable1452;

This will produce the following output −

+------------------+---------------------+-------------------+
| NumberOfRedColor | NumberOfYellowColor | NumberOfBlueColor |
+------------------+---------------------+-------------------+
|                2 |                   3 |                 2 |
+------------------+---------------------+-------------------+
1 row in set (0.27 sec)

Updated on: 10-Dec-2019

560 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements