簡體   English   中英

mysql group by on sum列

[英]mysql group by on sum column

我遇到的情況是,大學的學生會對某個主題進行研究。 每個主題都有一些價值(標記)。 一個學生可以對多個主題進行研究。

我具有以下表層次結構:

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”值的列進行分組?

嘗試這個:

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

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM