Counting with condition in MySQL?

MySQLMySQLi Database

To count, use aggregate function SUM() and to count with condition, you need to set the condition with WHERE. Let us first create a table −

mysql> create table DemoTable1515
   -> (
   -> ClientId varchar(10),
   -> ClientName varchar(20)
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1515 values('CLI-101','Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1515 values('CLI-110','David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1515 values('CLI-101','Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1515 values('CLI-101','Sam');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1515 values('CLI-101','Sam');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1515 values('CLI-101','Mike');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1515 values('CLI-130','Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1515 values('CLI-101','Chris');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable1515 values('CLI-101','Sam');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1515;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
| CLI-101  |    Chris   |
| CLI-110  |    David   |
| CLI-101  |      Bob   |
| CLI-101  |      Sam   |
| CLI-101  |      Sam   |
| CLI-101  |     Mike   |
| CLI-130  |     Mike   |
| CLI-101  |     Chris  |
| CLI-101  |      Sam   |
+----------+------------+
9 rows in set (0.00 sec)

Here is the query to count with condition −

mysql> select ClientId,sum(ClientName='Sam') as NameOn101Id,count(*) as TotalNameOn101 from DemoTable1515
   -> where ClientId='CLI-101';

This will produce the following output −

+----------+-------------+----------------+
| ClientId | NameOn101Id | TotalNameOn101 |
+----------+-------------+----------------+
| CLI-101  |           3 |              7 |
+----------+-------------+----------------+
1 row in set (0.00 sec)
raja
Published on 11-Dec-2019 06:18:06
Advertisements