我正在寻找一些关于如何开始寻找尝试对查询中的公共(public)键行进行排名的基本方向。
假设我有一个这样的表:
user_id | account_id | score
1 A 10
1 B 20
2 C 10
2 D 20
2 E 30
我希望做的是为每个 user_id
添加一个排名列,其中最高分获得最高排名:
user_id | account_id | score | rank
1 A 10 2
1 B 20 1
2 C 10 3
2 D 20 2
2 E 30 1
只是寻找一些基本的方向:/
最佳答案
可以使用子查询
select
*,
(select count(1)+1 from your_table b where a.user_id=b.user_id and a.score<b.score) as rank
from your_table a
输出
1 A 10 2
1 B 20 1
2 C 10 3
2 D 20 2
2 E 30 1
关于MySQL 给定键的所有出现在一列中的值的相对排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52323558/