select 年级,count(1),
count(case when 性别='男' then 1 else null end),
count(case when 性别='女' then 1 else null end)
from B
group by 年级得到上面的结果,再用a表left join 一下上面的即可

解决方案 »

  1.   

    --drop table a,bcreate table A(年级 varchar(20))insert into A
    select '一年级' union all
    select '二年级' union all
    select '三年级' union all
    select '四年级' union all
    select '五年级' union all
    select '六年级'create table B(姓名 varchar(10), 性别 varchar(10), 年级 varchar(10))insert into B
    select '李明',    '男'     ,'一年级' union all
    select '张杰',    '男'     ,'二年级' union all
    select '赵丽',    '女'     ,'一年级' union all
    select '刘琴',    '女'     ,'一年级' union all
    select '杨刚',    '男'     ,'五年级' union all
    select '周丽',    '女'     ,'六年级'
    go
    select a.年级,
           COUNT(B.姓名) 总人数,
           sum(case when 性别='男' then 1 else 0 end) 男,
           sum(case when 性别='女' then 1 else 0 end) 女
    from A
    left join B
           on a.年级 = b.年级
    group by a.年级
    /*
    年级 总人数 男 女
    二年级 1 1 0
    六年级 1 0 1
    三年级 0 0 0
    四年级 0 0 0
    五年级 1 1 0
    一年级 3 1 2
    */
      

  2.   

    但是这个如果要按照一,二,三来排序,那么最好在A表中增加一个id字段,1,2,3,这样就容易拍虚了