获取日期序列中的所有缺失日期

时间:2016-10-03 21:49:34

标签: sql amazon-redshift paraccel

我试图在一系列日期中按升序排列所有缺少的日期。如何在不使用任何函数或udfs的情况下使用简单的sql来完成。

Input :-

2016-09-01
2016-09-02
2016-09-05
2016-09-10

输出: -

2016-09-03
2016-09-04
2016-09-06
2016-09-07
2016-09-08
2016-09-09

我尝试了什么?

  select start, stop 
    from
       (
          select m.x + 1 as start,
                 (select min(x) - 1 from X as x where x.x > m.x) as stop
            from X as m
           left outer join X as r
              on m.x = r.x - 1
           where r.x is null
        ) as x
  where stop is not null;

1 个答案:

答案 0 :(得分:-1)

  1. 创建一个新表并插入365行编号为1-365 (或者使用已经超过365行的表并使用rownum或类似的构造来获得唯一的整数)

  2. 将日期转换为整数(在Oracle中使用类似TO_CHAR( mydate, 'ddd' )的内容)

  3. 在查询中将这两个列表连接在一起以查找相应的集合(重叠,缺失等)

  4. 转换回日期