Multiple COUNT() for multiple conditions in a single MySQL query?

MySQLMySQLi Database

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY.

The syntax is as follows -

SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName;

To understand the above syntax, let us first create a table. The query to create a table is as follows.

mysql> create table MultipleCountDemo
-> (
-> Id int,
-> Name varchar(100),
-> Age int
-> );
Query OK, 0 rows affected (2.17 sec)

Insert records in the table using insert command. The query is as follows.

mysql> insert into MultipleCountDemo values(1,'Carol',21);
Query OK, 1 row affected (0.27 sec)

mysql> insert into MultipleCountDemo values(2,'Sam',21);
Query OK, 1 row affected (0.29 sec)

mysql> insert into MultipleCountDemo values(3,'Bob',22);
Query OK, 1 row affected (0.10 sec)

mysql> insert into MultipleCountDemo values(4,'John',23);
Query OK, 1 row affected (0.24 sec)

mysql> insert into MultipleCountDemo values(5,'David',22);
Query OK, 1 row affected (0.12 sec)

mysql> insert into MultipleCountDemo values(6,'Adam',22);
Query OK, 1 row affected (0.21 sec)

mysql> insert into MultipleCountDemo values(7,'Johnson',23);
Query OK, 1 row affected (0.14 sec)

mysql> insert into MultipleCountDemo values(8,'Elizabeth',23);
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement. The query is as follows -

mysql> select *from MultipleCountDemo;

The following is the output.

+------+-----------+------+
| Id | Name | Age |
+------+-----------+------+
| 1 | Carol | 21 |
| 2 | Sam | 21 |
| 3 | Bob | 22 |
| 4 | John | 23 |
| 5 | David | 22 |
| 6 | Adam | 22 |
| 7 | Johnson | 23 |
| 8 | Elizabeth | 23 |
+------+-----------+------+
8 rows in set (0.00 sec)

Now here is the query for multiple count() for multiple conditions in a single query.

mysql> select Age,count(*)as AllSingleCount from MultipleCountDemo group by Age;

The following is the output.

+------+----------------+
| Age | AllSingleCount |
+------+----------------+
| 21 | 2 |
| 22 | 3 |
| 23 | 3 |
+------+----------------+
3 rows in set (0.00 sec)
raja
Published on 11-Jan-2019 10:06:22
Advertisements