通过跳过一行来查询组

时间:2012-08-14 07:26:18

标签: php mysql

我有一张桌子

students[std_id, name, class, gender,etc]

select class,gender,count(*) as total_students 
from students 
group by class,gender

其输出如下

 1st | male   | 23   
 1st | female | 11   
 2nd | male   | 17   

 2nd | female | 0   

//最后一行未显示,因为第二类的0名女学生

如何使用total_sudents = 0而不是跳过记录来显示它。

2 个答案:

答案 0 :(得分:4)

您可以通过为每个性别编写查询然后将它们合并来执行此操作:

select class, 'male' as gender, 
    count(case when gender = 'male' then 1 end) as total_students 
from students 
group by class

union all

select class, 'female' as gender, 
    count(case when gender = 'female' then 1 end) as total_students 
from students 
group by class

或者,您可以这样做:

select class, 
    count(case when gender = 'male' then 1 end) as total_male_students,
    count(case when gender = 'female' then 1 end) as total_female_students  
from students 
group by class

答案 1 :(得分:2)

使用此解决方案:

SELECT    a.class,
          a.gender,
          COUNT(b.class) AS total_students
FROM      (
          SELECT     a.class, 
                     b.gender
          FROM       students a
          CROSS JOIN (
                     SELECT 'male' AS gender UNION ALL 
                     SELECT 'female'
                     ) b
          GROUP BY   a.class, 
                     b.gender
          ) a
LEFT JOIN students b ON a.class = b.class AND 
                        a.gender = b.gender
GROUP BY  a.class,
          a.gender