查找列中的第一个缺失日期(Oracle)

时间:2016-10-06 08:29:26

标签: sql oracle plsql

我需要在plan_table表的日期列中找到第一个缺少的日期。不应该在holiday_table中,也不应该属于任何周末。

holiday_table存储所有假日日期。

Plan_table包含日期。在这里我们必须找到第一个缺失的日期

Plan_id      Date 
1           10/2/2016
2           10/3/2016
3           10/6/2016
4           10/9/2016
5           10/10/2016
6           10/12/2016
7           10/13/2016
8           10/16/2016

这里第一个缺少的日期是10/4/2016,但是如果这个日期在holiday_table中,那么我们必须显示10/5/2016或下一次出现..

请帮我写一个相同的查询。

1 个答案:

答案 0 :(得分:1)

您可以像这样使用LEAD分析功能

 select d
 from 
  (
    select
      date + 1  as d
    from 
    (
      select 
        date, 
        lead(date) over(order by date)  as next_date
        from 
        (
          select date   from plan_table
        union
          select date from holliday_table
         )
      order by date
    )
    where 
      trunc(date) + 1 < trunc(next_date)
    order by d 
  )
  where rownum = 1
 ;