2017-05-08 64 views
-2

我想排列以下得分表,其中相同的得分將具有相同的等級。rank()函數SQL

+----+-------+ 
| Id | Score | 
+----+-------+ 
| 1 | 3.50 | 
| 2 | 4.00 | 
| 3 | 4.00 | 
| 4 | 3.50 | 
+----+-------+ 

有人可以幫助爲什麼是以下查詢拋出語法錯誤?另外,邏輯不正確?

代碼:

select Score, RANK() OVER (order by Score desc) as rank 
from Scores 
order by Score desc; 

錯誤消息:

Line 1: SyntaxError: near '(order by Score desc) as rank 
from Scores 
order by Score desc' 
+3

MYSQL犯規支持窗口功能尚未 – GurV

+0

啊哈相關的一些注意事項 - 這就是了。謝謝! –

回答

1

如:(假設你想和1居第2,而不是1和3)

SELECT x.* 
    , CASE WHEN @prev = score THEN @i:[email protected] ELSE @i:[email protected]+1 END rank 
    , @prev:=score 
    FROM my_table x 
    , (SELECT @prev:=null,@i:=0) vars 
ORDER 
    BY score DESC 
    , id; 

對於體育排名,你可以這樣做:

SELECT a.* 
    , FIND_IN_SET(score, 
        (SELECT GROUP_CONCAT(score ORDER BY score DESC) 
         -- inclusion of DISTINCT here will output as above 
         FROM my_table) 
        ) x 
    FROM my_table a; 

但也有與此解決方案

+0

我認爲'cross join'會比''更好,'。 – Blank

+0

這真的很聰明!不可讀,但不錯 – AxelH

+0

@Forward。不,這是一樣的。 – Strawberry