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

測試共有4個部分,每個部分都有不同的問題。 我想知道,對於每個學生和每個部分,他們正確回答了多少問題(響應= 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條件。

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

如果您有一個包含學生信息的單獨表格,您可以從該表格中選擇學生並將結果連接到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

這樣,它首先選擇所有學生,然后執行count命令。

暫無
暫無

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

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