我需要使用 sql 查找基本日期范围和测试范围之间的差距。这是我的示例 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 但他们没有像我这样的场景。
最佳答案
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
关于sql - 在 Oracle 中使用 sql 查找日期范围中的差距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15487186/