MySQL uses group by grouping to implement the first N records

Source: Internet
Author: User

MySQL GROUP by group takes the first N records implementation

MySQL group, Fetch Records

How to take the first two bits of each group after group by I'll tell you how to implement the first N records of the group by group in MySQL.

This is the test table (also do not know how to think, then the table name directly knocked a AA, sweat ~ ~ ~):

Results:

Method One:

SELECT A.id,a.sname,a.clsno,a.score from AA a left JOIN AA B on A.clsno=b.clsno and A.score<b.score GROUP by A.id,a.sna Me,a.clsno,a.score has count (b.id) <2 ORDER by A.clsno,a.score Desc

  

Disassembly Analysis:

Left joins AA B on A.clsno=b.clsno and A.score<b.score

The same class (four per class), the score is higher than the current student record, that means that the bottom of the students, will produce three records

GROUP BY A.id,a.sname,a.clsno,a.score have Count (b.id) <2
A.id,a.sname,a.clsno,a.score can represent a student (in groups of students), if Count (b.id) <2 (no more than 2 people), then only the first second is left.

Method Two:

SELECT * from AA a WHERE 2> (select COUNT (*) from AA where Clsno=a.clsno and Score>a.score) ORDER by A.clsno,a.score DESC;

This I think is more interesting, take each record, judge the same class, greater than the current grade of students is not less than 2 people.

 

MySQL uses group by grouping to implement the first N records

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.