Perform multiple counting without using MySQL COUNT()?

MySQLMySQLi Database

To count, you can use SUM() along with CASE statement for conditions. Let us first create a table −

mysql> create table DemoTable1485
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> StudentSubject varchar(20)
   -> );
Query OK, 0 rows affected (0.72 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','MySQL');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Robert','MongoDB');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','Java');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1485;

This will produce the following output −

+-----------+-------------+----------------+
| StudentId | StudentName | StudentSubject |
+-----------+-------------+----------------+
|         1 | Chris       |          MySQL |
|         2 | Robert      |        MongoDB |
|         3 | Robert      |        MongoDB |
|         4 | Chris       |           Java |
+-----------+-------------+----------------+
4 rows in set (0.00 sec)

Here is the query to perform multiple counting without using COUNT() method −

mysql> select StudentSubject,
   -> sum(case when StudentName = 'Chris' THEN 1 ELSE 0 END) Chris_Count,
   -> sum(case when StudentName = 'Robert' THEN 1 ELSE 0 END) Robert_Count
   -> from DemoTable1485
   -> group by StudentSubject;

This will produce the following output −

+----------------+-------------+--------------+
| StudentSubject | Chris_Count | Robert_Count |
+----------------+-------------+--------------+
| MySQL          |           1 |            0 |
| MongoDB        |           0 |            2 |
| Java           |           1 |            0 |
+----------------+-------------+--------------+
3 rows in set (0.00 sec)
raja
Published on 10-Dec-2019 08:16:47
Advertisements