Selecting the top occurring entries in MySQL from a table with duplicate values?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable610 (SubjectName varchar(100));
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable610 values('MySQL');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable610 values('Java');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable610 values('MySQL');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable610 values('MongoDB');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable610 values('MySQL');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable610 values('MySQL');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable610 values('Java');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable610 values('MongoDB');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable610 values('C');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable610 values('C++');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable610 values('MongoDB');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable610 values('MySQL');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable610 values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable610 values('Python');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable610 values('MySQL');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable610;

This will produce the following output −

+-------------+
| SubjectName |
+-------------+
| MySQL       |
| Java        |
| MySQL       |
| MongoDB     |
| MySQL       |
| MySQL       |
| Java        |
| MongoDB     |
| C           |
| C++         |
| MongoDB     |
| MySQL       |
| Java        |
| Python      |
| MySQL       |
+-------------+
15 rows in set (0.00 sec)

Here is the query to select only the top occurring entries −

mysql> select SubjectName from ( select SubjectName from DemoTable610 group by SubjectName order by count(SubjectName) DESC LIMIT 2 ) AS tbl order by SubjectName;

This will produce the following output −

+-------------+
| SubjectName |
+-------------+
| Java        |
| MySQL       |
+-------------+
2 rows in set (0.04 sec)
raja
Published on 22-Aug-2019 16:43:01
Advertisements