2014-09-17 10 views
0

나는 대학생들이 주제에 관한 연구를하는 시나리오를 가지고있다. 각 과목마다 약간의 가치 (마크)가 있습니다. 한 학생이 여러 과목을 연구 할 수 있습니다.mysql 그룹 by sum 칼럼

나는 다음과 같은 테이블 계층 구조가이 같은 결과를 얻을 수

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 (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 
.... 

지금 내가이 쿼리와 총 연구 값과 함께 학생 기록을 가져 오는 오전 다음 :

student_id total 

1   10 
2   25 
3   25 
4   30 

결과는 student_id으로 그룹화되어 있습니다. 하지만 내가 원하는 것은 합계를 값으로 그룹화하는 것입니다. 그래서 나는 합계에 대한 중복 행을 없애고 싶습니다. (즉, 합계가 25 인 경우 1 레코드 만).

나는 사용하여 시도 : 그룹을 총에 의해 (대신 student_id에 의해 그룹의) 쿼리에서,하지만 오류가 있습니다. 'sum'값이 포함 된 열을 기준으로 결과를 그룹화하는 다른 방법이 있습니까?

+0

할 수 있습니다 별칭에 의해 그룹화하지, 합으로 그룹을 시도 (r.value) – Aramillo

+0

반환 할 쿼리에서 학생 ID가 예상되는 중복 합계 값은? –

+0

@MKhalidJunaid 모든 학생 ID (2 또는 3)를 반환 할 수 있습니다. –

답변

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 
+0

이것은 잘 해결되었습니다. 작업 쿼리를 사용하여 대답을 편집했습니다. –

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 
+0

심지어 이렇게 작동하지만 내부 쿼리에 대한 별칭을 추가해야했습니다. 경고 메시지가 나타납니다. 파생 테이블마다 고유 한 별칭이 있어야합니다. –