Count occurrences of known distinct values in MySQL


For this, you can use aggregate function SUM(). Let us first create a table −

mysql> create table DemoTable636 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentFirstName varchar(100)
);
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable636(StudentFirstName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Sam');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Mike');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable636(StudentFirstName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable636(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable636;

This will produce the following output −

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
|         1 | John             |
|         2 | Robert           |
|         3 | Robert           |
|         4 | Sam              |
|         5 | Mike             |
|         6 | John             |
|         7 | Robert           |
+-----------+------------------+
7 rows in set (0.00 sec)

Following is the query to count occurrences of known (or enumerated) distinct values −

mysql> select
   sum(StudentFirstName='John') AS JOHN_COUNT,
   sum(StudentFirstName='Robert') AS ROBERT_COUNT,
   sum(StudentFirstName='Sam') AS SAM_COUNT,
   sum(StudentFirstName='Mike') AS MIKE_COUNT
   from DemoTable636;

This will produce the following output −

+------------+--------------+-----------+------------+
| JOHN_COUNT | ROBERT_COUNT | SAM_COUNT | MIKE_COUNT |
+------------+--------------+-----------+------------+
|          2 |            3 | 1         | 1          |
+------------+--------------+-----------+------------+
1 row in set (0.00 sec)

Updated on: 02-Jul-2020

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements