我有一个包含列 (userid, score)
的 MYSQL 表。我想对 userid
进行分组,并得到一个列,其中包含每个 userid
的 X 个最高分数的总和。
例如对于两个最高分的总和:
userid | score
-------+-------
01 | 1
01 | 1
01 | 2
02 | 1
02 | 2
02 | 3
到:
userid | scoresum
-------+----------
01 | 3
02 | 5
但我似乎无法弄清楚如何在 MYSQL 中执行此操作。
最佳答案
select
userid,
(
select sum(highestscores)
from (
select *
from userscore us2
where us2.userid = us1.userid
order by score desc limit 5
)
) as scoresum
from ( select distinct userid from userscore ) us1
所以基本上你需要一个子查询来获得 5 个最高分。然后将它们与另一个子查询相加。并且您从唯一的表 userscore 为每个唯一的 user_id 运行整个业务。
关于mysql - mysql中每行最高x的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6427012/