首页 > 解决方案 > 在 sqlite 中选择最大值的总和

问题描述

基于下表架构,我希望能够选择每次提交的最大值之和。一个学生可以有多个参赛作品,因此他们的总分是每场比赛的最高分之和。现在我的查询选择了他们所有比赛的 student_id、姓名和最高分,我怎样才能得到他们所有比赛的最高分的总和?基于输入的预期输出应该是:

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;

标签: sqlsqlite

解决方案


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


推荐阅读