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

Ci sono 4 sezioni sul test, ognuna con un diverso numero di domande. Voglio sapere, per ogni studente e ogni sezione, quante domande hanno risposto correttamente (risposta = 1).mysql SELECT COUNT (*) ... GROUP BY ... non restituisce righe dove il conteggio è zero

Tuttavia, con questa query, se uno studente non fa domande direttamente in una determinata sezione, quella riga sarà completamente mancante dal mio set di risultati. Come posso assicurarmi che per ogni studente vengano sempre restituite 4 righe, anche se il "totale" di una riga è 0?

Ecco ciò che il mio set di risultati assomiglia:

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 

Grazie per qualsiasi visione!

UPDATE: Ho provato

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

e che non ha modificato i risultati a tutti. Altre idee?

UPDATE 2: I got it grazie al lavoro per la risposta di seguito:

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

È necessario mostrare l'aspetto dell'ingresso. –

risposta

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 

Nota che non c'è WHERE condizione.

+1

il codice CASE WHEN era esattamente ciò di cui avevo bisogno. Grazie! – Jen

0

se si dispone di un tavolo separato con le informazioni sugli studenti, è possibile selezionare gli studenti di quel tavolo e di sinistra unire i risultati al data_raw tavolo:

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 

In questo modo, si seleziona prima tutti gli studenti, poi esegue il comando di conteggio.

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