Rank Scores(分数排序)

问题:

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.

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
数据表:

Create table If Not Exists Scores (Id int, Score DECIMAL(3,2))
Truncate table Scores
insert into Scores (Id, Score) values ('1', '3.5')
insert into Scores (Id, Score) values ('2', '3.65')
insert into Scores (Id, Score) values ('3', '4.0')
insert into Scores (Id, Score) values ('4', '3.85')
insert into Scores (Id, Score) values ('5', '4.0')
insert into Scores (Id, Score) values ('6', '3.65')

解决办法一:

SET @rownum=0;
SELECT a.score,b.rank FROM scores a,
   (SELECT a.score,@rownum:=@rownum+1 AS rank FROM 
	(SELECT score FROM scores GROUP BY score) a
	 ORDER BY a.score DESC) b 
WHERE a.Score=b.score 
ORDER BY score DESC;


解决办法二:

SELECT a.score,b.rank FROM scores a,
   (SELECT a.score,@rownum:=@rownum+1 AS rank FROM 
	(SELECT score FROM scores GROUP BY score) a,(SELECT   @rownum:=0)  t2 
	 ORDER BY a.score DESC) b 
WHERE a.Score=b.score 
ORDER BY score DESC;

解决办法三

SELECT
  Score,
  (SELECT count(distinct Score) FROM Scores WHERE Score >= s.Score) Rank
FROM Scores s
ORDER BY Score desc

猜你喜欢

转载自blog.csdn.net/qq_35448976/article/details/79505763
今日推荐