--列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.   

    select 
    sum(case when (a=1 and (b='x' or b='y')) or ( a<>1 and b='y') then 1 else 0 end)
    from tb 
      

  2.   

    楼主好像算错了.
    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 行受影响)
    */
      

  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] 
      

  4.   

    请大家看题目好吗  这题的SQL语句已经有很多人回答过啦  我想要的是下面的三个问题的答案  
    请看题再回答好吗!!!!
      

  5.   

    直接用sql里的条件语句就可以搞定了。代码引用楼上的。
    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
      

  6.   

    我觉得是LZ的union语句的运用有误,你在对三个查询做并操作时,三个表的属性个数和类型应该是一样的,而你第三个表有三个属性,所以无法显示
      

  7.   

    HAVING 子句对 GROUP BY 子句设置条件的方式与 WHERE 和 SELECT 的交互方式类似。WHERE 搜索条件在进行分组操作之前应用;而 HAVING 搜索条件在进行分组操作之后应用。HAVING 语法与 WHERE 语法类似,但 HAVING 可以包含聚合函数。HAVING 子句可以引用选择列表中显示的任意项.
    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
      

  8.   

    1.having 子句一般用于对统计值来进行处理,而不对列值进行处理,列值的条件应由where子句处理.即:
    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是有区别的.