开发者

sql query help on multiple count columns and group by

开发者 https://www.devze.com 2023-03-05 01:53 出处:网络
i have the following table Students: id | status | school | name ---------------------------- 0| fail| skool1 | dan

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

SE开发者_开发百科LECT 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?


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.


SELECT q.school, q.fail, q.failpass-q.fail as pass
FROM
  (
  SELECT s.school, sum(if(status = 'fail',1,0)) as fail, count(*) as failpass
  FROM students s
  GROUP BY s.school
  ) q

This way you save one conditional sum.
In MySQL a GROUP BY already orders the results, so a separate ORDER BY is not needed.

0

精彩评论

暂无评论...
验证码 换一张
取 消