简体   繁体   English

mysql SELECT COUNT(*)... GROUP BY ...不返回计数为零的行

[英]mysql SELECT COUNT(*) … GROUP BY … not returning rows where the count is zero

SELECT student_id, section, count( * ) as total
FROM raw_data r
WHERE response = 1
GROUP BY student_id, section

There are 4 sections on the test, each with a different number of questions. 测试共有4个部分,每个部分都有不同的问题。 I want to know, for each student, and each section, how many questions they answered correctly (response=1). 我想知道,对于每个学生和每个部分,他们正确回答了多少问题(响应= 1)。

However, with this query, if a student gets no questions right in a given section, that row will be completely missing from my result set. 但是,使用此查询,如果学生在给定部分中没有得到任何问题,那么我的结果集中将完全丢失该行。 How can I make sure that for every student, 4 rows are ALWAYS returned, even if the "total" for a row is 0? 我怎样才能确保每个学生总共返回4行,即使一行的“总数”为0?

Here's what my result set looks like: 这是我的结果集的样子:

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

Thanks for any insight! 感谢您的任何见解!

UPDATE: I tried 更新:我试过了

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

and that didn't change the results at all. 而这根本没有改变结果。 Other ideas? 其他想法?

UPDATE 2: I got it working thanks to the response below: 更新2:由于以下回复,我得到了它的工作:

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

Note that there's no WHERE condition. 请注意,没有WHERE条件。

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

if you have a separate table with student information, you can select students from that table and left join the results to the data_raw table: 如果您有一个包含学生信息的单独表格,您可以从该表格中选择学生并将结果连接到data_raw表:

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

This way, it first selects all students, then executes the count command. 这样,它首先选择所有学生,然后执行count命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM