基于下表模式,我希望能够选择每次提交的最大值的总和。一个学生可以为一场比赛提交多份参赛作品,因此他们的总分是每次比赛的最高分数之和。现在,我的查询选择了他们所有比赛的student_id、name和最高分,我如何获得他们所有比赛最高分的总和?基于输入的预期输出应为:
select student_id, name, max(score) as TotalScore
from students2 as st
join submissions as s
where st.student_id = s.student_id
group by st.student_id, name
having count(*) > 1
order by TotalScore desc;
select student_id, name, sum(TotalScore) total_sum
from (select st.student_id student_id
, name
, max(score) as TotalScore
from students as st
join submissions as s
on st.student_id = s.student_id
group by s.contest_id, s.student_id)
group by student_id;
这是一个演示
我已经开始在你的样本数据之前创建一个演示。。。
从你问题中的文本来看,我不明白你需要having count(*) > 1
做什么,所以我没有使用它。
请注意:我使用了students
作为表的名称,而不是students2
。
使用两个级别的聚合:
select student_id, name, sum(max_score) as TotalScore
from students2 st join
(select s.student_id, max(score) as max_score
from submissions s
group by s.student_id
) s
on st.student_id = s.student_id
group by st.student_id, name
having count(*) > 1;
order by TotalScore desc;
我注意到您的FROM
子句使用JOIN
,但缺少ON
子句。你应该习惯于总是这样。