SQL - 填写没有结果的日期

时间:2012-09-09 21:42:56

标签: sql oracle

我有这个问题:

Select Trunc(Create_Dtime),Count(Trunc(Create_Dtime)) as Day_0 From Player
Group By Trunc(Create_Dtime)
Order By Trunc(Create_Dtime) Asc

它给了我回溯日期,但如果日期没有任何结果,则跳过。我想填写从8-05到现在的所有日期,如果那些日子没有任何值,那么结果中只有0。

1 个答案:

答案 0 :(得分:1)

根据您希望如何创建它们,您可以创建calender table或使用Oracle connect by语法动态生成行。

with the_dates as (
  select max(trunc(Create_Dtime)) as max_date
       , min(trunc(Create_Dtime)) as min_date
    from player 
         )
  , generator as (
  select min_date + level as the_date
    from the_dates
 connect by level <= max_date
         )
select g.the_date, count(trunc(p.Create_Dtime))
  from generator g
  left outer join player p
    on g.the_date = trunc(p.Create_Dtime)
 group by g.the_date
 order by g.the_date desc

如果您按下日历表选项,它会更清洁一点:

with the_dates as (
  select max(trunc(Create_Dtime)) as max_date
       , min(trunc(Create_Dtime)) as min_date
    from player 
         )
select c.the_date, count(trunc(p.Create_Dtime))
  from calender c
  join the_dates td
    on c.the_date between td.min_date and td.max_date
  left outer join join player p
    on c.the_date = trunc(p.Create_Dtime)
 group by c.the_date
 order by c.the_date

或者,刚刚注意到你的日期限制:

with the_dates as (
  select to_date('07-05-2012','dd-mm-yyyy') + level as the_date
    from dual
 connect by level <= trunc(to_date('07-05-2012','dd-mm-yyyy') - sysdate)
         )
 select td.the_date, count(trunc(p.create_dtime))
   from the_dates td
   left outer join player p
     on td.the_date = trunc(p.create_dtime)
  group by td.the_date
  order by td.the_date

对于所有这些,我建议在trunc(create_dtime)表格上的player上添加一个索引。