如何在 Oracle table 中查找月份间隔?

How to find month gaps in Oracle table?

我有一个 Oracle table,它有 EmpName (Char)、Month_from 和 Month_to 列(数字)。在这里我需要找到缺失的月份(月份差距)。在下面的示例数据中,我必须找到缺失的第 6 个月(6 月)。

提前致谢。

Sample Data:

|-------|-----------|--------|
|eName  |Month_From |Month_To|
|(Char) | ( Int)    | ( Int) |
|-------|------------|-------|
|John   |1          |2       | ( Jan to Feb)
|John   |3          |5       | ( Mar to May)
|John   |7          |8       | ( Jul to Aug)    
|-------|------------|-------|

需要查找(Jun 到 Jun)。

只是样本数据的转换,你可以考虑:

select to_char(to_date(lpad(t.month_from,2,'0'),'mm'),'Mon')||' to '||
       to_char(to_date(lpad(t.month_to,2,'0'),'mm'),'Mon')
  from my_table t
 where upper(t.eName) = upper('&i_eName');

对于问题(六月到六月):

select to_char(to_date(lpad(a1.mon,2,'0'),'mm'),'Mon')
  from ( select level mon from dual connect by level <= 12 ) a1
 where not exists ( select null
                      from my_table a2
                     where a1.mon between a2.month_from and a2.month_to
                       and upper(a2.eName) = upper('&i_eName') )
 order by mon;

但是,它 returns 也 9 月10 月11 月12 月,此外 6 月。为此,我同意@mathguy 的评论。

假设没有重叠,您可以使用 lag():

找到缺失的月份
select (prev_month_to + 1) as start_missing,
       (month_from - 1) as end_missing
from (select t.*, lag(month_to) over (partition by name order by month_from) as prev_month_to
      from t
     ) t
where prev_month_to <> month_from - 1;

这为每个差距提供了一个范围,因为差距可能超过一个月。