mysql實現排名

2021-10-05 03:09:41 字數 2481 閱讀 1093

心血來潮刷了一波leetcode,遇見個有意思的sql題目。

題目連線:

編寫乙個 sql 查詢來實現分數排名。

如果兩個分數相同,則兩個分數排名(rank)相同。請注意,平分後的下乙個名次應該是下乙個連續的整數值。換句話說,名次之間不應該有「間隔」。

±—±------+

| id | score |

±—±------+

| 1 | 3.50 |

| 2 | 3.65 |

| 3 | 4.00 |

| 4 | 3.85 |

| 5 | 4.00 |

| 6 | 3.65 |

±—±------+

例如,根據上述給定的 scores 表,你的查詢應該返回(按分數從高到低排列):

±------±-----+

| score | rank |

±------±-----+

| 4.00 | 1 |

| 4.00 | 1 |

| 3.85 | 2 |

| 3.65 | 3 |

| 3.65 | 3 |

| 3.50 | 4 |

±------±-----+

一、先搞個順序排名,分數相等順序排名

select

a.score,

@rownum1 :=

@rownum1+1

as rank

from

scores a,

(select

@rownum1 :=

0) b

order

by a.score desc

;

(select @rownum1 :=0) b 的作用是:

在同乙個select語句中給變數rownum1 賦初始值。

等同於,兩個sql語句,第乙個先賦值,第二個再select.

二、實現同分數同名次

引入乙個變數記錄當前行score的值,如果下一行score值等於變數值,rownum1 不增加,否則rownum1 +1,且重新為變數賦值當前score值。

select

a.score,

case

when a.score =

@rownum2

then

@rownum1

when

@rownum2 := a.score then

@rownum1 :=

@rownum1+1

endas rank

from

scores a,

(select

@rownum1 :=0,

@rownum2 :=

null

) b

order

bya.score desc

;

三、這裡有個坑,score為0的行返回null

score為0時不走任何分支直接返回了null,case when後增加else @rownum1:=@rownum1+1

select

a.score,

case

when a.score =

@rownum2

then

@rownum1

when

@rownum2 := a.score then

@rownum1 :=

@rownum1+1

else

@rownum1 :=

@rownum1+1

endas rank

from

scores a,

(select

@rownum1 :=0,

@rownum2 :=

null

) b

order

bya.score desc

;

或者使用if函式

select

t.score,

t.rank

from

(select

a.score,

if( a.score =

@rownum2

,@rownum1+0

,@rownum1 :=

@rownum1+1

)as rank,

@rownum2 := a.score

from

scores a,

(select

@rownum1 :=0,

@rownum2 :=

null

) b

order

by a.score desc

) t;

if(a>1,a,b): 如果為真返回a,否則返回b。這裡返回的@rownum1是字串,題目要求排名使用數字,所以在@rownum1 後+ 0,rownum1 會轉成數字。

mysql 排名 MySQL用變數實現排名

mysql 8.0版本用視窗函式就可以實現排名,有三種方式,對相同值的處理不同 以上區別會在文末舉例,本文主要討論用變數實現排名 5.5版本用不了視窗函式 至少排序視窗用不了,其他的沒試過 那麼對於要顯示排名的需求就得想其他辦法啦,看網上的資料可以用變數來實現,來看看 首先建表並插入資料 資料資料來...

mysql 排名函式 MySQL排名函式實現

資料庫準備 建立乙個分數表s score create table s score id int not null auto increment,score int not null default 0,name varchar 20 character set utf8mb4 null,prima...

mysql排名的實現

首先我們先建立 create table user info id bigint 20 not null auto increment comment 自增id nick name varchar 255 default null comment 暱稱 create date datetime de...