Implement multiple COUNT() in a single MySQL query

MySQLMySQLi Database

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

mysql> create table DemoTable
   -> (
   -> LastName varchar(100)
   -> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Smith');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('Brown');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('Brown');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('Smith');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('Taylor');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('Taylor');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values('Miller');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values('Miller');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values('Miller');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----------+
| LastName |
+----------+
| Smith    |
| Brown    |
| Brown    |
| Smith    |
| Taylor   |
| Taylor   |
| Miller   |
| Miller   |
| Miller   |
+----------+
9 rows in set (0.00 sec)

Following is the query to implement multiple COUNT() methods in one query −

mysql> select COUNT(CASE WHEN LastName='Smith' THEN 1 END) AS TotalFrequency,
-> COUNT(CASE WHEN LastName='Brown' THEN 1 END) AS TotalFrequency,
-> COUNT(CASE WHEN LastName='Taylor' THEN 1 END) AS TotalFrequency,
-> COUNT(CASE WHEN LastName='Miller' THEN 1 END) AS TotalFrequency
-> from DemoTable;

Output

This will produce the following output −

+----------------+----------------+----------------+----------------+
| TotalFrequency | TotalFrequency | TotalFrequency | TotalFrequency |
+----------------+----------------+----------------+----------------+
| 2              | 2              | 2              | 3              |
+----------------+----------------+----------------+----------------+
1 row in set (0.00 sec)
raja
Published on 09-Jul-2019 14:22:00
Advertisements