MySQL query to count occurrences of distinct values and display the result in a new column?



Let us first create a table −

mysql> create table DemoTable (    Value int ); Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(80); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(80); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+ | Value | +-------+ |    80 | |    90 | |    90 | |    80 | |    100| |    90 | +-------+ 6 rows in set (0.00 sec)

Following is the query to count occurrences of distinct values −

mysql> select Value,count(*) from DemoTable group by Value;

This will produce the following output −

+-------+----------+ | Value | count(*) | +-------+----------+ |    80 |       2 | |    90 |       3 | |   100 |       1 | +-------+----------+ 3 rows in set (0.00 sec)
Updated on: 2019-10-10T12:31:39+05:30

593 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements