Is it possible to combine 'DISTINCT' and 'COUNT' queries, so that I can see how many times each distinct value appears in a MySQL table column?

MySQLMySQLi Database

Yes, you can use aggregate function COUNT(*) along with GROUP BY clause. Let us first create a −

mysql> create table DemoTable1425
   -> (
   -> JoiningYear int
   -> );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1425 values(2000);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1425 values(2010);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1425 values(2015);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1425 values(2000);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1425 values(2010);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1425 values(2000);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1425 values(2010);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select −

mysql> select * from DemoTable1425;

This will produce the following output −

+-------------+
| JoiningYear |
+-------------+
|        2000 |
|        2010 |
|        2015 |
|        2000 |
|        2010 |
|        2000 |
|        2010 |
+-------------+
7 rows in set (0.00 sec)

Following is the query to see how many times each distinct value appears −

mysql> select JoiningYear,count(*) from DemoTable1425 group by JoiningYear;

This will produce the following output −

+-------------+----------+
| JoiningYear | count(*) |
+-------------+----------+
|        2000 |        3 |
|        2010 |        3 |
|        2015 |        1 |
+-------------+----------+
3 rows in set (0.00
raja
Published on 12-Nov-2019 10:16:01
Advertisements