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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章