MySQL implementation row_number () grouping sorting function

Source: Internet
Author: User

Database Basic Script

CREATE TABLE ' A ' (' ID ' int () null default NULL, ' class ' int (TEN) null default NULL, ' score ' int (TEN) null default NULL) COLLA Te= ' Utf8_general_ci ' Engine=innodb;insert into a values (1,1,110); insert into a values (2,1,120); insert into a values (3,1, Insert into a values (4,1,140), insert into a values (5,2,210), insert into a values (6,2,220), insert into a values (7, 2,230) insert into a values (8,2,240), insert into a values (9,3,310), insert into a values (10,3,320), insert into a values (11,4,410);

1. Group class to take the first 2 of each group

Select Id,class,score,rank from (select B.id,b.class,b.score, @rownum: [Email protected]+1, if (@pdept =b.class, @rank: [ Email protected]+1, @rank: =1) as rank, @pdept: =b.classfrom (select Id,class,score from a order by ID) b, (select @rownum: = 0, @pdept: = null, @rank: =0) c) resulthaving rank <3;

Rank <3 refers to the month ruwnum<3 each group is automatically given the serial number. How many records are numbered. refers to each group.

2. The class is grouped to record two days, that is, rownum=2 data

Select Id,class,score,rank from (select B.id,b.class,b.score, @rownum: [Email protected]+1, if (@pdept =b.class, @rank: [ Email protected]+1, @rank: =1) as rank, @pdept: =b.classfrom (select Id,class,score from a order by score Desc) b, (select @r Ownum: =0, @pdept: = null, @rank: =0) c) resulthaving rank = 2;

  

MySQL implementation row_number () grouping sorting function

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.