1

我想编写一个 MySQL 查询来对分数进行排名。如果两个分数之间存在平局,则两者的排名应相同。同样在平局之后,下一个排名数字应该是下一个连续的整数值。换句话说,等级之间不应该有“漏洞”。

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

给定上述分数表,查询应生成以下报告(按最高分排序)

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

我尝试了类似下面的设置@pk1 =''; 设置@rn1 =1;设置@val = 1;

SELECT  score,Rank
 FROM
 (
  SELECT  score,
      @rn1 := if(@pk1=score,@rn1, @rn1+@val) as Rank,
      @val := if(@pk1=score,@val+1, 1 ) as value,
      @pk1 := score

  FROM
(SELECT  score FROM scores ORDER BY score) as rank) as scores;

但上述没有用任何人都可以帮助解决这个问题

4

0 回答 0