使用mysql根据用户的最大得分计算他们的排名

yduiuuwa  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(385)

我有一个表(称为用户),我需要根据他们的得分排名用户,但我想排名的基础上,用户的最大得分。

+-----------+------------+
| User_id   | Score      |
+-----------+------------+
| 1         | 12258      | 
| 1         | 112        |
| 2         | 9678       |
| 5         | 9678       |
| 3         | 689206     |
| 3         | 1868       |

预期结果

+-----------+------------+---------+
| User_id   | Score      | Rank    |
+-----------+------------+---------+
| 3         | 689206     |   1     |     
| 1         | 12258      |   2     |
| 2         | 9678       |   3     |
| 5         | 9678       |   3     |
wn9m85ua

wn9m85ua1#

你在找什么 DENSE_RANK ,但支持8.0以上的mysql版本
使用相关子查询获取 max 按每个值 User_id 使用两个变量一个存储 rank 另一个用于存储以前的值以使 DENSE_RANK 号码。
像这样。

CREATE TABLE T(
   User_id int,
   Score int
); 

insert into t values (1,12258); 
insert into t values (1,112);
insert into t values (2,9678);
insert into t values (5,9678);
insert into t values (3,689206);
insert into t values (3,1868);

查询1:

SELECT User_id,Score,Rank
FROM (
  SELECT User_id,
         Score,
         @rank :=IF(@previous = t1.score, @rank, @rank + 1) Rank,
         @previous := t1.Score
  FROM T t1 CROSS JOIN (SELECT @Rank := 0,@previous := 0) r
  WHERE t1.Score = 
  (
    SELECT  MAX(Score)  
    FROM T tt
    WHERE t1.User_id = tt.User_id
  ) 
  ORDER BY Score desc
) t1

结果:

| User_id |  Score | Rank |
|---------|--------|------|
|       3 | 689206 |    1 |
|       1 |  12258 |    2 |
|       2 |   9678 |    3 |
|       5 |   9678 |    3 |
rqqzpn5f

rqqzpn5f2#

MySQL5.7中计算密集秩的另一个技巧(如MySQL8中)是在使用变量赋值时使用case。

SELECT User_id, MaxScore AS Score,
  CASE 
  WHEN MaxScore = @prevScore THEN @rnk
  WHEN @prevScore := MaxScore THEN @rnk := @rnk+1 
  ELSE @rnk := @rnk+1
  END AS Rank
FROM 
(
  SELECT User_id, MAX(Score) AS MaxScore
  FROM YourTable
  GROUP BY User_id
  ORDER BY MaxScore DESC, User_id
) AS q
CROSS JOIN (SELECT @rnk := 0, @prevScore := null) AS vars

你可以在rextester上测试。

相关问题