数据库

sql查询一个班级中总共有多少人以及男女分别多少人

2014-03-03

--创建视图

 
 create  view StuClassView as
  SELECT s.ID ,s.StuName ,s.StuAge ,s.StuAddress ,s.StuTel ,s.ClassId ,s.StuId,s.StuSex ,e.ClassName,e.ClassInfo,e.ClassFlag
  FROM Classes as e left  join   Students as s on s.ClassId=e.ClassId


Select sc.ClassName as '班级名称',count(sc.StuId) as '总人数' ,sum(case when sc.StuSex='男' then 1 else 0 end) as '男',
 sum(case when sc.StuSex='女' then 1 else 0 end) as '女' from StuClassView as sc  group by sc.ClassName