gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:01:50 25 4
gpt4 key购买 nike

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

测试分为 4 个部分,每个部分都有不同数量的问题。我想知道,对于每个学生和每个部分,他们正确回答了多少个问题 (response=1)。

但是,对于此查询,如果学生在给定部分没有正确回答问题,则该行将完全从我的结果集中丢失。我怎样才能确保对于每个学生,总是返回 4 行,即使一行的“总计”为 0?

这是我的结果集:

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:由于以下回复,我让它工作了:

 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

请注意,没有 WHERE 条件。

关于sql - mysql SELECT COUNT(*) ... GROUP BY ...不返回计数为零的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1478384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com