【问题标题】:Find Gaps in Date Ranges using sql in Oracle在 Oracle 中使用 sql 查找日期范围中的空白
【发布时间】:2013-03-18 21:22:00
【问题描述】:

我需要使用 sql 查找基准范围和测试范围的 DateRanges 之间的差距。这是我的示例 SD 和 ED 是开始和结束日期。 A 和 B 的所有行都在同一个表中。

A 的日期

ID    SD            ED
 A   20130101      20130531
 A   20130601      20131031

B 的日期

 ID  SD            ED
 B   20130120      20130420
 B   20130601      20130830
 B   20130910      20131130
Output should be: 
the Dates that are in A but are not in B with no dates overlaps

缺失的差距范围

SD           ED
20130101     20130119
20130421     20130531
20130831     20130909

我在这里查看了一些示例 http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:529176000346581356 但他们没有像我这样的场景。

【问题讨论】:

    标签: sql oracle datetime plsql gaps-and-islands


    【解决方案1】:
    select 
       to_char(SD, 'yyyymmdd') as SD,
       to_char(ED, 'yyyymmdd') as ED
    from
       (  -- prepare gaps in each A after removing all B
          select
             BED + 1 as SD,
             lead(BSD, 1, AED + 1) over (partition by ASD,AED order by BSD) - 1 as ED
          from
             (  -- prepare all intersections between A and B
                select AA.sd as ASD, AA.ed as AED, BB.sd as BSD, BB.ed as BED
                from AA join BB on least(AA.ed, BB.ed) >= greatest(AA.sd, BB.sd)
                union all
                select AA.sd, AA.ed, to_date('1000','yyyy'), AA.sd - 1
                from AA
             )
       )   
    where SD <= ED  -- exclude empty gaps
    order by 1
    

    fiddle

    【讨论】:

    • 这很棒。多谢!!!!。我的数据是整数,而不是 Db 和单个表中的日期,您可以在此添加 cmets 以了解在此执行的操作吗?
    • @NatashaThapa - 将数字转换为日期:to_date(number, 'yyyymmdd'),将日期转换为数字:to_number(to_char(date, 'yyyymmdd'))
    • 如果我必须更改,您能否添加一些关于 sql 的每个部分在做什么的 cmets
    • 如果您一开始在 A 中有重叠并且您想避免在 B 中重叠,该如何处理
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    相关资源
    最近更新 更多