--列a 列b
--1 x
--2 x
--1 y
--2 y
--3 x
--1 y
--3 x
--1 x
--要求:如果a=1 计算列b是‘x’或‘y'的个数; 如果a不等于1 只计算 是y的个数。写出sql查询语句
--结果:
--a b
--1 3
--2 1
--3 0我的写法:select a,count(a) b
from t1
group by a
having a='1'
union
select a,count(a) b
from t1
group by a,b
having a='2' and b='y'
union
select a ,count(b) b --,count(a) b
from t1
group by a,b
having a='3' and b='y'问题是:
最后结果中a=3 的一列不显示 请解释一下啊 ?是不是count中算的结果为零就不显示呢 ?select a ,count(b) b
from t1
group by a
having a='3' and b='y'
这个语法有错误 是不是having子句中出现的字段 一定要是group by 或 聚合函数 中的出现过的字段呢 ?
--1 x
--2 x
--1 y
--2 y
--3 x
--1 y
--3 x
--1 x
--要求:如果a=1 计算列b是‘x’或‘y'的个数; 如果a不等于1 只计算 是y的个数。写出sql查询语句
--结果:
--a b
--1 3
--2 1
--3 0我的写法:select a,count(a) b
from t1
group by a
having a='1'
union
select a,count(a) b
from t1
group by a,b
having a='2' and b='y'
union
select a ,count(b) b --,count(a) b
from t1
group by a,b
having a='3' and b='y'问题是:
最后结果中a=3 的一列不显示 请解释一下啊 ?是不是count中算的结果为零就不显示呢 ?select a ,count(b) b
from t1
group by a
having a='3' and b='y'
这个语法有错误 是不是having子句中出现的字段 一定要是group by 或 聚合函数 中的出现过的字段呢 ?
sum(case when (a=1 and (b='x' or b='y')) or ( a<>1 and b='y') then 1 else 0 end)
from tb
create table tb1(a int,b varchar(10))
insert into tb1 select 1,'x'
insert into tb1 select 2,'x'
insert into tb1 select 1,'y'
insert into tb1 select 2,'y'
insert into tb1 select 3,'x'
insert into tb1 select 1,'y'
insert into tb1 select 3,'x'
insert into tb1 select 1,'x'
go
select a,sum(case when a=1 and (b='x' or b='y') then 1 else (case when a<>1 and b='y' then 1 else 0 end)end)as b
from tb1 group by a
/*
a b
----------- -----------
1 4
2 1
3 0(3 行受影响)
*/
select a,
sum(case when (a=1 and (b='x' or b='y')) or ( a<>1 and b='y') then 1 else 0 end)
from [tb]
请看题再回答好吗!!!!
select a,sum(case when a=1 and (b='x' or b='y') then 1 else (case when a<>1 and b='y' then 1 else 0 end)end)as b
from tb1 group by a
select a,countB=sum(case b when 'x' then 1 when 'y' then 1 else 0 end) from tb where a=1 group by a
union all
select a,countB=count(case b when 'y' then 1 else 0 end) from tb where a!=1 group by a
select a,count(a) b
from t1
where a='1'
group by a
用having的话,应类似于
having count(*)>0
2.由于你的数据中没有满足条件的记录,统计值为空,所以得不到当a='3'时的统计值.
3.写成:
select a ,sum(case when b='y' then 1 else 0 end) b
from t1
where a='3'
group by a
就能得到你要的结果.
注意,NULL与0是有区别的.