sql - 在 Oracle 中使用 sql 查找日期范围中的差距

标签 sql oracle datetime plsql gaps-and-islands

我需要使用 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

fiddle

关于sql - 在 Oracle 中使用 sql 查找日期范围中的差距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15487186/

相关文章:

sql - 错误: No unique constraint matching given keys for referenced table

mysql - 删除电子邮件不是已知电子邮件客户端的位置

c# - 将我的 DataGridView 绑定(bind)到引用游标

java.sql.SQLException : Connection is closed

sql - 获取日期范围内的日期

sql - 子过程过程是否可以锁定并修改其调用过程已锁定的相同行进行更新?

python - cx_Oracle.InterfaceError : Unable to acquire Oracle environment handle Mac

sql - 转换日期时间 (YYYY-MM-DD HH :MM:SS) to decimal for openquery to progress database

c# - 将日期 yyyyMMdd 转换为 system.datetime 格式

mysql - 如何像在 mysql 中一样在 postgresql 中列出所有列及其引用?