存在一个表:
id 流水号 姓名 性别 借阅类型
1 1 tom 男 书
2 2 tom 男 书
3 3 jone 女 书
4 4 jone 女 报
5 5 jone 女 书希望能写一个count(*) 查询来取得男性的借书总条数与女性的借书总条数,得到如下结果:
男 女
书 2 2
id 流水号 姓名 性别 借阅类型
1 1 tom 男 书
2 2 tom 男 书
3 3 jone 女 书
4 4 jone 女 报
5 5 jone 女 书希望能写一个count(*) 查询来取得男性的借书总条数与女性的借书总条数,得到如下结果:
男 女
书 2 2
[男]=sum(case when 性别='男' then 1 else 0 end),
[女]=sum(case when 性别='女' then 1 else 0 end)
from [Table]
group by 借阅类型
sum(case when 性别='女' then 1 else 0 end) 女
from tb where 借阅类型='书'
select 借阅类型,
sum(case when 性别='男' then 1 else 0 end) [男],
sum(case when 性别='女' then 1 else 0 end) [女]
from tb
where 借阅类型='书'
group by 借阅类型
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)
*/
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
select
sum(case when seg='男' and lx='书' then 1 else 0 end )男,
sum(case when seg='女' and lx='书' then 1 else 0 end )女
from 表
select
sum(case [性别] when '男' then 1 else 0 end) as 男,
sum(case [性别] when '女' then 1 else 0 end) as 女 from #
where 借阅类型 = '书'
sum(case when 性别='女' then 1 else 0 end) 女
from #1 where 借阅类型='书'
group by 借阅类型