★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-eplnfzth-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.git
+----+-------+ | Id | Score | +----+-------+ | 1 | 3.50 | | 2 | 3.65 | | 3 | 4.00 | | 4 | 3.85 | | 5 | 4.00 | | 6 | 3.65 | +----+-------+
For example, given the above Scores
table, your query should generate the following report (order by highest score):github
+-------+------+ | Score | Rank | +-------+------+ | 4.00 | 1 | | 4.00 | 1 | | 3.85 | 2 | | 3.65 | 3 | | 3.65 | 3 | | 3.50 | 4 | +-------+------+
編寫一個 SQL 查詢來實現分數排名。若是兩個分數相同,則兩個分數排名(Rank)相同。請注意,平分後的下一個名次應該是下一個連續的整數值。換句話說,名次之間不該該有「間隔」。微信
+----+-------+ | Id | Score | +----+-------+ | 1 | 3.50 | | 2 | 3.65 | | 3 | 4.00 | | 4 | 3.85 | | 5 | 4.00 | | 6 | 3.65 | +----+-------+
例如,根據上述給定的 Scores
表,你的查詢應該返回(按分數從高到低排列):spa
+-------+------+ | Score | Rank | +-------+------+ | 4.00 | 1 | | 4.00 | 1 | | 3.85 | 2 | | 3.65 | 3 | | 3.65 | 3 | | 3.50 | 4 | +-------+------+
137ms
1 # Write your MySQL query statement below 2 Select Score, 3 @rank:=@rank + (@pre<>(@pre:=Score)) as Rank 4 From Scores, (Select @rank:=0, @pre:=-1) INIT 5 Order by Score DESC;
139mscode
1 # Write your MySQL query statement below 2 3 select f.score Score, f.Rank from 4 (select 5 @rnk:=@rnk + case when @score > s.score then 1 else 0 end as Rank 6 ,@score:= s.score as score 7 from 8 (select score from scores order by score desc) s,(select @score:=0,@rnk:=1) t) f
142mshtm
1 # Write your MySQL query statement below 2 Select Score, 3 @rank:=@rank + (@pre<>(@pre:=Score)) as Rank 4 From Scores, (Select @rank:=0, @pre:=-2) INIT 5 Order by Score DESC;
143msblog
1 # Write your MySQL query statement below 2 SELECT 3 Score, 4 @rank := @rank + (@prev <> (@prev := Score)) Rank 5 FROM 6 Scores, 7 (SELECT @rank := 0, @prev := -1) init 8 ORDER BY Score desc
146msget
1 # Write your MySQL query statement below 2 select Score, CONVERT(Rank, SIGNED) AS Rank from ( 3 select Score, 4 if(Score = @previous_score, @rank := @rank, @rank := @rank +1) as Rank, 5 @previous_score := score 6 from Scores, (select @rank := 0, @previous_score:= null) r 7 order by Score desc)v
552ms博客
1 # Write your MySQL query statement below 2 3 SELECT s.Score, count(distinct t.score) Rank 4 FROM Scores s JOIN Scores t ON s.Score <= t.score 5 GROUP BY s.Id 6 ORDER BY s.Score desc
553ms
1 # Write your MySQL query statement below 2 SELECT s1.Score, count(distinct s2.Score) as Rank 3 FROM Scores s1 4 join Scores s2 on s1.Score <= S2.Score 5 GROUP BY s1.Id 6 ORDER BY 2