title isshow_num noshow_num
a 2 1
b 1 0
c 1 1
d 1 0
应该怎么写这个多条件分组语句啊?
...全文
3876打赏收藏
SQL多条件分组问题,请教各位前辈。
一个表,只有两个字段title、ifshow;结构如下(ifshow为状态) title ifshow a 1 b 1 c 0 d 1 a 0 a 1 c 1 现在要求,分别统计ifshow=1和ifshow=0两种状态下title字段里的统计值,要求查询生成以下数据集 title isshow_num noshow_num a 2 1 b 1 0 c 1 1 d 1 0 应该怎么写这个多条件分组语句啊?
create table test(
title varchar(5),
ifshow bit
)
insert into test
select 'a',1 union all
select 'b',1 union all
select 'a',0 union all
select 'd',1 union all
select 'b',1
select title,count((case when ifshow=1 then 1 end)) isshow_num,count((case when ifshow=0 then 1 end)) noshow_num
from test
group by title
select a.title,isshow_num = (select count(1) from 表 b where b.title = a.title and a.ifshow = 1),noshow_num = (select count(1) from 表 b where b.title = a.title and a.ifshow = 0) from 表 a
select title,
isshow_num = sum(case when ifshow = 1 then 1 else 0 end),
noshow_num = sum(case when ifshow = 0 then 1 else 0 end)
from table group by title