存在一个表:
id        流水号      姓名       性别        借阅类型
1            1       tom       男           书
2            2       tom       男           书
3            3       jone      女           书
4            4       jone      女           报
5            5       jone      女           书希望能写一个count(*) 查询来取得男性的借书总条数与女性的借书总条数,得到如下结果:
   男    女
书  2    2

解决方案 »

  1.   

    select 借阅类型,
           [男]=sum(case when 性别='男' then 1 else 0 end),
           [女]=sum(case when 性别='女' then 1 else 0 end)
    from [Table]
    group by 借阅类型
          
      

  2.   

    select 借阅类型,sum(case when 性别='男' then 1 else 0 end) 男,
        sum(case when 性别='女' then 1 else 0 end) 女
    from tb where 借阅类型='书'
      

  3.   


    select 借阅类型,
           sum(case when 性别='男' then 1 else 0 end) [男],
           sum(case when 性别='女' then 1 else 0 end) [女]
    from tb
    where 借阅类型='书'
    group by 借阅类型
      

  4.   

    select 男=(select count(1) from tb where 性别='男' and 借阅类型='书'),女=(select count(1) from tb where 性别='女' and 借阅类型='书')
      

  5.   

    楼上的需要加group by 借阅类型
      

  6.   

    select 男=sum(case when 性别='男'  and 借阅类型='书' then 1 else 0 end),女=sum(case when 性别='女'  and 借阅类型='书' then 1 else 0 end) from tb
      

  7.   

    create table #1(id  int, 流水号 int,姓名 varchar(10), 性别 varchar(10), 借阅类型  varchar(10))
    insert #1 values(1,            1,      'tom' ,     '男',         '书') 
    insert #1 values(2,            2,      'tom' ,     '男',         '书') 
    insert #1 values(3,            3,      'jone',      '女',          '书') 
    insert #1 values(4,            4,      'jone',      '女',          '报') 
    insert #1 values(5,            5,      'jone',      '女',          '书')select 
    男 = sum(case when(性别='男' and 借阅类型 ='书') then 1 else 0 end),
    女 = sum(case when(性别='女' and 借阅类型 ='书') then 1 else 0 end)
    from #1
    group by 性别/*
    男           女
    ----------- -----------
    2           0
    0           2(2 row(s) affected)
    */
      

  8.   

    declare @t table (id int ,id1 varchar(4),name1 varchar(8),seg varchar(2),lx varchar(4))
    insert into @t
    select 1,'1','tom','男','书' union all
    select 2,'2','tom','男','书' union all
    select 3,'3','tom','女','书' union all
    select 4,'4','tom','女','报' union all
    select 5,'5','tom','女','书' select 
    sum(case when seg='男' and lx='书' then 1  else 0 end )男,
    sum(case when seg='女' and lx='书' then 1  else 0 end )女
    from @t
      

  9.   


    select 
    sum(case when seg='男' and lx='书' then 1  else 0 end )男,
    sum(case when seg='女' and lx='书' then 1  else 0 end )女
    from 表
      

  10.   


    select 
    sum(case [性别] when '男' then 1 else 0 end) as 男,
    sum(case [性别] when '女' then 1 else 0 end) as 女 from # 
    where 借阅类型 = '书'
      

  11.   

    select 借阅类型,sum(case when 性别='男' then 1 else 0 end) 男,
        sum(case when 性别='女' then 1 else 0 end) 女
    from #1 where 借阅类型='书'
    group by 借阅类型