Mysql group by top N

Source: Internet
Author: User

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

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.