MySQL ranking SQL statement notation

Source: Internet
Author: User

Typically, when using MySQL, you will find a ranking of data based on multiple ranking criteria, with the same conditions.

Suppose there are table tables, two criteria fields Conditiona descending sort and conditionb ascending sort, the same conditions are the same, ranking information is saved in the Dense_rank field.

Procedure: Define @Conditiona, @conditionb, @dense_rank, @id_rank four user variables. where @Conditiona, @conditionB to save the current row of data conditions , @dense_rank to save the current rank value,@id_rank to save the ordinal, Query results according to ORDER by Conditiona Desc, conditionb ASC, the final wording is as follows, mainly using case end.

SELECT

Case

When @Conditiona =-1 and @conditionb =-1 Then @dense_rank: = 1 #判断是否第一个记录, is ranked first

When @Conditiona = Conditiona and @conditionb = conditionb /c8> then @dense_rank #判断当前记录是否与之前的一样, is to keep the rankings unchanged

ELSE @dense_rank: = @dense_rank + 1 #其他情况, rank plus 1

END as Dense_rank,

@id_rank: = @id_rank +1 as I_rank, #递增序号字段

@Conditiona : = Conditiona as Conditiona, #更新条件变量为当前记录的值

@conditionb : = conditionb as conditionb # update condition variable is the value of the current record

From

(SELECT @id_rank: =0) I_rank, # Initialize ordinal variable

(SELECT @dense_rank: =0) d, #初始化排名变量

(SELECT @conditionA: =-1) s, # Initialize condition variable

(SELECT @conditionb: =-1) C, # Initialize condition variable

Table

ORDER BY Conditiona DESC, conditionb ASC




MySQL ranking SQL statement notation

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.