Use ORDER BY with DESC to order in descending order. For counting the values, use the COUNT(). For example, if the name “John” appears thrice in the column, then a separate column will display the count 3 and in this way all the count values will be arranged in descending order using the ORDER BY DESC.
Let us first create a table −
mysql> create table DemoTable -> ( -> EmployeeName varchar(100) -> ); Query OK, 0 rows affected (0.85 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.31 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+--------------+ | EmployeeName | +--------------+ | Sam | | David | | David | | Chris | | Robert | | Chris | | Sam | | Sam | | David | | Robert | | David | | Chris | +--------------+ 12 rows in set (0.00 sec)
Following is the query to get the count of values and display the count in a new column ordered in descending order −
mysql> select EmployeeName,count(EmployeeName) as Total from DemoTable -> group by EmployeeName -> order by Total DESC;
Output
+--------------+-------+ | EmployeeName | Total | +--------------+-------+ | David | 4 | | Chris | 3 | | Sam | 3 | | Robert | 2 | +--------------+-------+ 4 rows in set (0.00 sec)