2009-09-25 2 views
5
SELECT student_id, section, count(*) as total 
FROM raw_data r 
WHERE response = 1 
GROUP BY student_id, section 

각기 다른 수의 질문이있는 테스트 섹션이 4 개 있습니다. 나는 각 학생과 각 섹션에 대해 그들이 얼마나 정확하게 대답했는지 (응답 = 1) 알고 싶다.mysql SELECT COUNT (*) ... GROUP BY ... 개수가 0 인 행을 반환하지 않음

그러나이 쿼리를 사용하면 주어진 섹션에서 학생이 아무런 질문도받지 못하면 해당 행이 내 결과 집합에서 완전히 사라집니다. 행에 대한 "합계"가 0 인 경우에도 모든 학생에게 4 행이 항상 반환되도록하려면 어떻게해야합니까?

여기 내 결과 집합의 모습입니다 : 어떤 통찰력에 대한

student_id section  total 
1   DAP--29  3 
1   MEA--16  2 
1   NNR--13  1 --> missing the 4th section for student #1 
2   DAP--29  1 
2   MEA--16  4 
2   NNR--13  2 --> missing the 4th section for student #2 
3   DAP--29  2 
3   MEA--16  3 
3   NNR--13  3 --> missing the 4th section for student #3 
4   DAP--29  5 
4   DAP--30  1 
4   MEA--16  1 
4   NNR--13  2 --> here, all 4 sections show up because student 4 got at least one question right in each section 

감사합니다!

업데이트 : 나는

SELECT student_id, section, if(count(*) is null, 0, count(*)) as total 

을 시도하고는 전혀 결과를 변경하지 않았다. 다른 아이디어?

업데이트 2 : 나는 아래의 반응 덕분에 작업 있어요 : 더 WHERE 조건이 없다는 것을

SELECT student_id, section, SUM(CASE WHEN response = '1' THEN 1 ELSE 0 END) AS total 
FROM raw_data r 
WHERE response = 1 
GROUP BY student_id, section 
+0

입력 내용을 표시해야합니다. –

답변

9
SELECT student_id, section, sum(case when response=1 then 1 else 0 end) as total 
FROM raw_data_r GROUP BY student_id, section 

참고. 다음 실행,

SELECT si.student_name, rd.student_id, rd.section, rd.count(*) AS total 
    FROM student_info AS si LEFT JOIN raw_data AS rd USING rd.student_id = si.student_id 

이 방법은, 먼저 모든 학생을 선택 : 당신이 학생 정보를 별도의 테이블이있는 경우

+1

CASE WHEN 코드가 필요한 코드입니다. 감사! – Jen

0

, 당신은 data_raw 테이블에 결과를 조인 테이블에서 학생을 선택하고 왼쪽 있습니다 카운트 명령.

1
SELECT r.student_id, 
      r.subject, 
      sum(r.response) as total 
     FROM raw_data r 
    GROUP BY student_id, subject