2

I need to find Gaps between DateRanges of base and test ranges using sql.here is my example SD and ED are start and End Dates. all rows for both A and B are in same table.

A's Date

ID    SD            ED
 A   20130101      20130531
 A   20130601      20131031

B's Date

 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

Missing Gap Ranges

SD           ED
20130101     20130119
20130421     20130531
20130831     20130909

i looked at some example in here http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:529176000346581356 but they did not scenario like mine.

4

1 回答 1

3
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

于 2013-03-18T22:28:48.547 回答