数据库查询语句,在线等

来源:百度知道 编辑:UC知道 时间:2024/06/02 14:26:31
现在一张学生信息表:students
内容为: Sno Sname Ssex Sdept
S01 张三 男 计科
S01 李四 女 农学
S03 王五 男 园林
S04 郑六 女 艺术
请问如何查询:分别统计每个系(Sdept)男女生的人数,要求输出为以下格式
Sdept 男生人数 女生人数
计科 1 0
农学 1 0
我写了个不知道怎么不对:Select Sdept,count(Sno) as '男生人数' where Ssex='男',count(Sno) as '女生人数' where Ssex='女'
from students
group by Sdept
本人菜鸟,请高手详解

select Sdept,(select count(1) from students s1 where s1.Ssex = '男' and s1.Sdept = s.Sdept) as '男',(select count(1) from students s2 where s2.Ssex = '女' and s2.Sdept = s.Sdept) as '女' from students s group by s.Sdept

PS:如果有错你可以自己检查,因为我没有经过测试

select Sdept,男生人数=sum(case when Ssex = '男' then 1 else 0 end),女生人数=sum(case when Ssex = '女' then 1 else 0 end) from [students ] group by Sdept