Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql query help on multiple count columns and group by

Tags:

sql

mysql

i have the following table Students:

id | status | school | name
----------------------------
0  | fail   | skool1 | dan
1  | fail   | skool1 | steve
2  | pass   | skool2 | joe
3  | fail   | skool2 | aaron

i want a result that gives me

school | fail | pass  
---------------------
skool1 | 2    | 0   
skool2 | 1    | 1    

I have this but it's slow,

SELECT s.school, (

SELECT COUNT( * ) 
FROM school
WHERE name = s.name
AND status = 'fail'
) AS fail, (

SELECT COUNT( * ) 
FROM school
WHERE name = s.name
AND status = 'pass'
) AS pass,

FROM Students s
GROUP BY s.school

suggestions?

like image 550
tipu Avatar asked Sep 14 '26 22:09

tipu


1 Answers

Something like this should work:

SELECT 
    school,
    SUM(CASE WHEN status = 'fail' THEN 1 ELSE 0 END) as [fail],
    SUM(CASE WHEN status = 'pass' THEN 1 ELSE 0 END) as [pass]
FROM Students
GROUP BY school
ORDER BY school

EDIT
Almost forgot, but you could also write the query this way:

SELECT 
    school,
    COUNT(CASE WHEN status = 'fail' THEN 1 END) as [fail],
    COUNT(CASE WHEN status = 'pass' THEN 1 END) as [pass]
FROM Students
GROUP BY school
ORDER BY school

I'm not sure if there's any performance benefit with second query. My guess would be if there is it's probably very small. I tend to use the first query because I think it's more clear but both should work. Also, I don't have a MySql instance handy to test with, but according to @Johan the ORDER BY clauses are unnecessary.

like image 154
rsbarro Avatar answered Sep 16 '26 17:09

rsbarro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!