1、假设有如下表
date           tag
20130101       0
20130101       1
20130102       0
20130101       1
20130103       1
20130101       0
20130103       1要求查询结果如下:
date        tag为1的出现次数   tag为0的出现次数
20130101           2                     2
20130102           0                     1
20130103           2                     02、再假设有如下表
date           tag
20130101       0
20130101       1
20130102       0
20130101       1
20130103       1
20130101       0
20130103       1
20130101       2
20130102       2
要求查询结果如下:
date        tag为1的出现次数   tag不为1的出现次数
20130101           2                     3
20130102           0                     2
20130103           2                     0求SQL实现语句,谢谢!OracleSQL分组查询

解决方案 »

  1.   


    with tb as(
    select 20130101 as a,0 as b from dual union all
    select 20130101,1 from dual union all
    select 20130102,0 from dual union all
    select 20130101,1 from dual union all
    select 20130103,1 from dual union all
    select 20130101,0 from dual union all
    select 20130103,1 from dual )
    select A,nvl(sum(case when b=1 then 1 else null end),0)
    ,nvl(sum(case when b=0 then 1 else null end),0) from tb
    group by a
    order by 1
    第一个这么写,第二个照着写就行..
      

  2.   

    理解了,昨天用的是grouping by ,没想到用nvl,多谢了!
    with tb as(
    select 20130101 as a,0 as b from dual union all
    select 20130101,1 from dual union all
    select 20130102,0 from dual union all
    select 20130101,1 from dual union all
    select 20130103,1 from dual union all
    select 20130101,0 from dual union all
    select 20130103,1 from dual  union all
    select 20130101,2 from dual  union all
    select 20130102,2 from dual 
     )
    select A,nvl(sum(case when b=1 then 1 else null end),0)
    ,nvl(sum(case when b != 1 then 1 else null end),0) from tb
    group by a
    order by 1 ;
      

  3.   

    补充一点,当 b 的值为null时,不包含在 b!=1 的条件之中,要改为
    case when b != 1 or b is null then 1 else null end