MySQL multiple COUNT with multiple columns?

MySQLMySQLi Database

You can use an aggregate function SUM() along with IF(). Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('John','Smith');
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (1.38 sec)
mysql> insert into DemoTable values('Bob','Doe');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Sam','Smith');
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Adam      | Smith    |
| John      | Smith    |
| John      | Doe      |
| Bob       | Doe      |
| Sam       | Smith    |
+-----------+----------+
5 rows in set (0.00 sec)

Here is the query to MySQL multiple COUNT with multiple columns.

mysql> select sum(if(FirstName='John',1,0)) as John_Count,
sum(if(LastName='Smith',1,0)) as Smith_Count from DemoTable;

This will produce the following output −

+------------+-------------+
| John_Count | Smith_Count |
+------------+-------------+
|         2 |            3 |
+------------+-------------+
1 row in set (0.00 sec)
raja
Published on 30-Sep-2019 10:34:23
Advertisements