0

我有一张桌子

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 使其如上所示,而不是跳过记录。

4

2 回答 2

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
于 2012-08-14T07:34:22.583 回答
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
于 2012-08-14T07:35:06.390 回答