如果可能,我想只通过一个查询获取结果集 我有这样的表
------------------------------
user_id | activity_id | score
------------------------------
1 | 1 | 100
------------------------------
1 | 1 | 50
------------------------------
1 | 2 | 20
------------------------------
1 | 3 | 10
------------------------------
1 | 3 | 50
------------------------------
2 | 1 | 300
------------------------------
3 | 3 | 10
------------------------------
3 | 2 | 40
------------------------------
我需要选择每个用户,并在每项活动中获得所有高分的总和。 例如,结果集应该是这样的:
------------------------------
user_id | score
------------------------------
1 | 170
------------------------------
2 | 300
------------------------------
3 | 50
------------------------------
答案 0 :(得分:2)
要获得每个用户/活动对的最高分,您可以使用以下查询:
select user_id, activity_id, max(score) as highscore
from t
group by user_id, activity_id;
要为给定用户添加这些内容,您可以将其作为子查询并执行另一个聚合:
select user_id, sum(highscore)
from (select user_id, activity_id, max(score) as highscore
from t
group by user_id, activity_id
) t
group by user_id;