To select the top 2 rows from each group, use the where condition with subquery. Let us create a table. The query to create a table is as follows:
mysql> create table selectTop2FromEachGroup -> ( -> Name varchar(20), -> TotalScores int -> ); Query OK, 0 rows affected (0.80 sec)
Now insert some records in the table using insert command. The query is as follows:
mysql> insert into selectTop2FromEachGroup values('John',32); Query OK, 1 row affected (0.38 sec) mysql> insert into selectTop2FromEachGroup values('John',33); Query OK, 1 row affected (0.21 sec) mysql> insert into selectTop2FromEachGroup values('John',34); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTop2FromEachGroup values('Carol',35); Query OK, 1 row affected (0.17 sec) mysql> insert into selectTop2FromEachGroup values('Carol',36); Query OK, 1 row affected (0.14 sec) mysql> insert into selectTop2FromEachGroup values('Carol',37); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from selectTop2FromEachGroup;
The following is the output:
+-------+-------------+ | Name | TotalScores | +-------+-------------+ | John | 32 | | John | 33 | | John | 34 | | Carol | 35 | | Carol | 36 | | Carol | 37 | +-------+-------------+ 6 rows in set (0.00 sec)
Here is the query to select top 2 rows from each group using where condition and subquery:
mysql> select *from selectTop2FromEachGroup tbl -> where -> ( -> SELECT COUNT(*) -> FROM selectTop2FromEachGroup tbl1 -> WHERE tbl1.Name = tbl.Name AND -> tbl1.TotalScores >= tbl.TotalScores -> ) <= 2 ;
The following is the output:
+-------+-------------+ | Name | TotalScores | +-------+-------------+ | John | 33 | | John | 34 | | Carol | 36 | | Carol | 37 | +-------+-------------+ 4 rows in set (0.06 sec)