我想在数据不存在的日期将数据设为零

时间:2014-10-07 07:20:21

标签: sql oracle

查询:

select logindate, count(*) as people 
from authortable 
group by logindate 
order by logindatedesc nulls last

输出:

logindate   people 
6-oct-2014    5
5-oct-2014    7
4-oct-2014    4
3-oct-2014    8
2-oct-2014    0
1-oct-2014    0
30-sept-2014  5
29-sept-2014  7
28-sept-2014  4
27-sept-2014  8

我正在获取我需要的数据,但我想要的东西好像在某一天没有登录,它应该返回0 ..如1和2 oct。我想得到1和2的数据,如上所示。

现在我没有得到1和2个oct行,因为没有数据

1 个答案:

答案 0 :(得分:1)

以下是生成缺少日期行的示例:

with daterange as
  (select min(logindate) startdate
        , max(logindate) enddate
   from authortable)
, dates as
  (select startdate + (level-1) logindate
   from daterange
   connect by startdate + (level-1) <= enddate)
, logincount as
  (select logindate
        , count(*) people
   from authortable
   group by logindate)
select d.logindate
     , nvl(l.people, 0) people
from logincount l
     right outer join dates d
       on (d.logindate = l.logindate)
order by d.logindate desc nulls last

编辑:添加了缺失的group_by(如nop77svk所述)