表结构:姓名,性别,部门
要求查询结果:部门,该部门男人数,该部门女人数,该部门总人数
                        ....
....
能用sql语句直接统计出来么?

解决方案 »

  1.   

    select 部门,部门男人数=(select Count(distinct 姓名) from test 
                             where 部门=a.部门 and 性别='男')
               ,部门女人数=(select Count(distinct 姓名) from test 
                             where 部门=a.部门 and 性别='女')
               ,部门总人数=(select Count(distinct 姓名) from test
                             where 部门=a.部门)
    from test as a
      

  2.   

    select 部门
           ,sum(case 性别 when '男' then 1 else 0 end) as 该部门男人数
           ,sum(case 性别 when '女' then 1 else 0 end) as 该部门女人数
           ,Count(*) as 该部门总人数
    from 表 group by 部门
      

  3.   

    select 部门,部门男人数=(select Count(distinct 姓名) from test 
                             where 部门=a.部门 and 性别='男')
               ,部门女人数=(select Count(distinct 姓名) from test 
                             where 部门=a.部门 and 性别='女')
               ,部门总人数=(select Count(distinct 姓名) from test
                             where 部门=a.部门)
    from test as a------------------这个应该对!
      

  4.   

    楼上的加入"group by 部门" 就更对了--人多力量大