合并两个表并查找重叠的日期和间隔

62lalag4  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(307)

我想使用oracle分析函数解决以下id 100和101的场景,作为给定的输出。有什么想法吗?
表a:

ID   ValidFrom   ValidTo
100  1/1/2009    12/31/2010
100  1/1/2011    3/31/2012
101  8/1/2013    7/31/2014
101  8/1/2014    8/31/2014

表b

ID   ValidFrom   ValidTo
100  11/1/2008   12/31/2011
100  2/1/2012    2/29/2012
101  8/1/2013    6/30/2014
101  7/1/2014    8/31/2014

输出:

ID   ValidFrom   ValidTo
100  11/1/2008  12/31/2008
100  1/1/2009   12/31/2010
100  1/1/2011   12/31/2011
100  1/1/2012   1/31/2012
100  2/1/2012   2/29/2012
100  3/1/2012   3/31/2012
---------------------------
101  8/1/2013   6/30/2014
101  7/1/2014   7/31/2014
101  8/1/2014   8/31/2014
busg9geu

busg9geu1#

此查询,使用分析 lead() 做这个工作。列 note 显示行是来自您的数据还是缺少间距:

select id, d1, d2, case dir when 3 then 'GAP' end note 
  from (
    select id, 
           case when dir = 2 
                 and lead(dir) over (partition by id order by dt) = 1
                 and lead(dt) over (partition by id order by dt) <> dt + 1
                then dt + 1 
                else dt
           end d1,
           case when dir = 2 
                 and lead(dir) over (partition by id order by dt) = 1
                 and lead(dt) over (partition by id order by dt) <> dt + 1
                then 3 
                else dir
           end dir,
           case when lead(dir) over (partition by id order by dt) = 1 
                then lead(dt)  over (partition by id order by dt) - 1
                else lead(dt)  over (partition by id order by dt) 
            end d2
      from (
        select * from a unpivot (dt for dir in (validfrom as 1, validto as 2)) union 
        select * from b unpivot (dt for dir in (validfrom as 1, validto as 2)) ) )
  where dir in (1, 3)

dbfiddle演示
一开始数据是不固定的,只是为了把所有的日期都放在一列中,这样更便于进一步分析。并集删除重复的值。列 dir 如果这是 from 或者 to 日期。那么 lead 根据该方向的类型,应用逻辑。我觉得可以简化一下:)

相关问题