我需要使用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
但他们并不像我一样。
答案 0 :(得分:2)
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