leecode_CN#178:分數排名

#178

  • 難度:中等
  • 知識點:分組、行號、排序、整型轉化、臨時表、賦值、比較
--1 我自己寫的:以爲會很慢,結果看着還好,87%
select ss.Score AS SCore, temp.num AS Rank
from Scores ss
left join (
    select a.Score,Cast(@i := @i + 1 AS SIGNED)   AS num
    from (
        select Score
        from Scores
        group by Score 
        order by Score DESC
    ) a,(SELECT @i:=0) as i
    group by a.Score 
    order by a.Score DESC

) temp on ss.Score=temp.Score
order by ss.SCore DESC

--2
select score, CAST(@a := @a + (@pre <> (@pre := Score)) AS SIGNED) as rank 
from scores,(select @a := 0, @pre := -1) t 
order by score desc; 


--窗口函數
select score, 
       dense_rank() over(order by Score desc) as Rank
from Scores;

--590ms
select 
    a.Score as score , 
    (select count(distinct b.Score) from Scores b where b.Score >=a.Score) as rank
from Scores a order by Score DESC;

cast

Cast(字段名 as 轉換的類型 ),其中類型可以爲:

CHAR[(N)] 字符型
DATE 日期型
DATETIME 日期和時間型
DECIMAL float型
SIGNED int
TIME 時間型

參考資料:

  • https://blog.csdn.net/m0_37450089/article/details/80750994
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章