Oracle加入双日期范围

时间:2016-11-01 10:27:49

标签: sql oracle join dual-table

我试图将数据放入双重查询的日期范围内。结果应如下所示:

SINGLEDAY       FLAG
01-NOV-2016     1
02-NOV-2016     -
03-NOV-2016     -
04-NOV-2016     1
05-NOV-2016     -

对于我使用

的日期列表
select (to_date('11.2016','mm.yyyy')+level-1) as SINGLEDAY
from dual
connect by level <= TO_CHAR(LAST_DAY(to_date('11.2016','mm.yyyy')),'DD')

但是如何将我的表xyz的内容与结果联系起来呢?表xyz应该通过DATE_OF_SERVICE(日期)列连接。任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

这基本上是您查询的left join。假设表中每行最多有一行:

with d as (
      select (to_date('09.2016','mm.yyyy')+level-1) as singleday
      from dual
      connect by level <= TO_CHAR(LAST_DAY(to_date('09.2016', 'mm.yyyy')), 'DD')
     )
select t.singleday,
       (case when t.date_of_service is not null then 1 end) as flag
from d left join
     t
     on d.singleday = t.date_of_service
order by d.singleday;

如果有倍数,那么也许你是group by

with d as (
      select (to_date('09.2016','mm.yyyy')+level-1) as singleday
      from dual
      connect by level <= TO_CHAR(LAST_DAY(to_date('09.2016', 'mm.yyyy')), 'DD')
     )
select t.singleday, count(t.date_of_service) as cnt
from d left join
     t
     on d.singleday = t.date_of_service
group by d.singleday
order by d.singleday;