Mysql group by top N is frequently used to query the first few groups in daily work. in oracle, row_num can be used to support queries. mysql currently does not support row_num. how can we meet this requirement? For example, data in a table:
+--------+-------+-----+| Person | Group | Age |+--------+-------+-----+| Bob | 1 | 32 || Jill | 1 | 34 || Shawn | 1 | 42 || Jake | 2 | 29 || Paul | 2 | 36 || Laura | 2 | 39 |+--------+-------+-----+
Expected results:
+--------+-------+-----+| Shawn | 1 | 42 || Jill | 1 | 34 || Laura | 2 | 39 || Paul | 2 | 36 |+--------+-------+-----+
Method 1: Use row_num in oracle to add pseudo columns to SQL.
set @num := 0, @group := '';select person, `group`, agefrom ( select person, `group`, age, @num := if(@group = `group`, @num + 1, 1) as row_number, @group := `group` as dummy from mytable order by `Group`, Age desc, person) as x where x.row_number <= 2;
Method 2: associate a subquery
SELECT a.person, a.group, a.age FROM person AS a WHERE (SELECT COUNT(*) FROM person AS b WHERE b.group = a.group AND b.age >= a.age) <= 2 ORDER BY a.group ASC, a.age DESC