最佳答案
对于 MySql 8.0,您可以使用 rank()
:
select
t.*,
rank() over (partition by t.level order by t.score DESC) `rank`
from tablename t
order by level, user
请参阅demo .
对于早期版本:
select
t.*,
(select count(*) from tablename where level = t.level and score > t.score) + 1 `rank`
from tablename t
请参阅demo .
结果:
| level | user | score | rank |
| ----- | ---- | ----- | ---- |
| 1 | A | 10 | 3 |
| 1 | B | 15 | 2 |
| 1 | C | 30 | 1 |
| 2 | A | 20 | 2 |
| 2 | B | 10 | 3 |
| 2 | C | 40 | 1 |
关于mysql - 如何在 SQL 表中存储用户在某个级别中的排名及其分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55772493/