MySQL rank function implementation _ MySQL

Source: Internet
Author: User
How does the rank function of MySQL implement the rank function of Mysql?-laruence learning Park-BlogJava

Http://www.blogjava.net/dunkbird/archive/2011/01/28/343718.html

Table features:

Mysql> select * from test;

+ ------ +
| A | B |
+ ------ +
| 1 | 20 |
| 1 | 21 |
| 1 | 24 |
| 2 | 20 |
| 2 | 32 |
| 2 | 14 |
+ ------ +
6 rows in set (0.00 sec)

Now, we use Group a to query the maximum two values of column B. How should I write this SQL statement?


1. create a table

Create Table: CREATE TABLE `sam` (  `a` int(11) DEFAULT NULL,  `b` int(11) DEFAULT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8

2. Insert analog data

INSERT INTO `sam` VALUES (1,10),(1,15),(1,20),(1,25),(2,20),(2,22),(2,33),(2,45);
+ ------ +
| A | B |
+ ------ +
| 1 | 10 |
| 1 | 15 |
| 1 | 20 |
| 1 | 25 |
| 2 | 20 |
| 2 | 22 |
| 2 | 33 |
| 2 | 45 |
+ ------ +

3. SQL implementation

select a,b,rownum,rank from     (select ff.a,ff.b,@rownum:=@rownum+1 rownum,if(@pa=ff.a,@rank:=@rank+1,@rank:=1) as rank,@pa:=ff.a     FROM       (select a,b from sam group by a,b order by a asc,b desc) ff,(select @rank:=0,@rownum:=0,@pa=null) tt) result    having rank <=2;

4. results:
+ ------ + -------- + ------ +
| A | B | rownum | rank |
+ ------ + -------- + ------ +
| 1 | 25 | 1 | 1 |
| 1 | 20 | 2 | 2 |
| 2 | 45 | 5 | 1 |
| 2 | 33 | 6 | 2 |
+ ------ + -------- + ------ +
4 rows in set (0.00 sec)

Note:

@ X is a variable,
X: = Y: assign Y to X

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.