日期:2014-05-17  浏览次数:20881 次

group by 后,结果结合的显示问题
select count(*) count,column_id from article where column_id in (100,101) group by column_id 
如果column_id 为100和101都有值的话,那么会打出类似如下结果

count column_id
3 100
5 101

但是假设column_id=100的没有结果集合,那执行上述语句后结果为
count column_id
5 101

但是我希望的是结果是这样
count column_id
0 100
5 101

也就是说即使没有结果,那我希望显示的是0,请问如何解决呢


------解决方案--------------------
SQL code
select b.c_id column_id,nvl(count(b.column_id),0) count 
from article a ,(select 100 c_id from dual
union all 
select 101 from dual 
) b
where a.column_id(+)=b.c_id 
group by b.c_id

------解决方案--------------------
count(字段)又不是统计字段里的内容啊
所以不管字段里什么内容,都可以统计的啊
------解决方案--------------------
column_id你最好做个关联表,存放你想要的列,这样2个表关联就可以查出任意多个为0行的数据了
------解决方案--------------------
比如说你的表里头没有102的column_id
SQL code
select count(t2.column_id) count, t3.column_id
  from (select t1.column_id, sum(t1.rn) over(order by t1.column_id) rn
          from (select t.column_id,
                       decode(t.rn - lag(rn, 1, -1)
                              over(partition by t.column_id order by
                                   t.column_id),
                              1,
                              0,
                              1) rn
                  from (select a.column_id,
                               row_number() over(partition by a.column_id order by a.column_id) rn
                          from article a
                         where a.column_id in (100, 101, 102)) t) t1) t2,
       (select t.column_id, rownum rn
          from (select 100 column_id
                  from dual
                union all
                select 101
                  from dual
                union all
                select 102 from dual) t) t3
 where t2.column_id(+) = t3.column_id
 group by t3.column_id