我有一个场景,一所大学的学生就某一主题进行研究。每个主题都有一些价值(标记)。学生可以对多个科目进行研究。
我有以下表格层次结构:
student (s)
---------------
student_id subject_id
1 2
2 1
2 3
3 1
3 3
4 2
4 3
.....
research_subjects (r)
-----------------------------
id value
1 5
2 10
3 20
4 40
....
现在,我正在通过此查询获取学生记录及其总研究价值:
select student_id, sum(r.value) as total from student s inner join research_subjects r on s.subject_id=r.id group by student_id
这给出了如下结果:
student_id total
1 10
2 25
3 25
4 30
如您所见,结果按 student_id 分组。但我想要的是按总值对结果进行分组。所以我想在输出中删除 total 的重复行。 (即只有1条记录,总数= 25)。
我尝试在查询中使用 group by total (而不是 group by student_id ),但它会出错。 是否有任何其他方法可以按照包含' sum'的列对结果进行分组?值?
答案 0 :(得分:2)
试试这个:
select count(student_id), total
from (
select student_id, sum(r.value) as total
from student s
inner
join research r on s.subject_id=r.id group by student_id
) s2
group by total
答案 1 :(得分:1)
试试这个:
select Count(student_id) as students, total
from
(
select student_id, sum(r.value) as total
from student s inner join research r on s.subject_id=r.id
group by student_id
) s
group by total
或者这个:
select Min(student_id) as student_id, total
from
(
select student_id, sum(r.value) as total
from student s inner join research r on s.subject_id=r.id
group by student_id
) s
group by total