在SQL艾伦的区间代数运算(Allen's Interval Algebra operati

2019-07-31 03:31发布

我一直在努力解决SQL几个棘手的问题,我需要从事件的时间间隔推断资产利用率,并刚刚了解艾伦的区间代数 ,这似乎是关键,解决这些问题。

代数描述13种间隔之间的关系的,并且下面的图像示出了第一7,其余为逆(即,X之前Y,Y满足X,等)

但我有麻烦找出如何执行相关操作。

由于我的样本数据,我怎么能去哪里弄个从以下三种类型的操作导致SQL或PLSQL?

  1. 防脱离
  2. 降低
  3. 寻找差距

请参阅我的SQLFiddle链接: http://sqlfiddle.com/#!4/cf0cc


原始数据

   start end width
[1]     1  12    12
[2]     8  13     6
[3]    14  19     6
[4]    15  29    15
[5]    19  24     6
[6]    34  35     2
[7]    40  46     7


操作1 - 脱开结果

我想查询以返回disjoint set从上面的数据,其中所有重叠的间隔已被分成行,使得没有重叠存在。

我怎么去这个SQL?

     start end width
[1]      1   7     7
[2]      8  12     5
[3]     13  13     1
[4]     14  14     1
[5]     15  18     4
[6]     19  19     1
[7]     20  24     5
[8]     25  29     5
[9]     34  35     2
[10]    40  46     7


操作2 - 减少结果

我该如何去减少/压扁的间隔,使得它们是:

  • 不为空(即,它们具有一个非空宽度);
  • 不重叠;
  • 从左至右排列;
  • 甚至不相邻(即,必须有2度连续的范围之间的一个非空的间隙)

在我的例子,这将是这样的:

    start end width
[1]     1  29    29
[2]    34  35     2
[3]    40  46     7


操作3 - 峡结果

另外,我如何才能找到差距?

   start end width
[1]    30  33     4
[2]    36  39     4

Answer 1:

这里是一个SQLFiddle演示 ,首先创建临时表来简化查询,尽管你可以把这些创作查询到最终的查询和做没有临时表:

create table t as select * from
(
select null s ,"start"-1 as e  from data
union all
select "start" s,null e  from data
union all
select "end"+1 s ,null e  from data
union all
select null s ,"end" e  from data
) d where exists (select "start" 
                  from data where d.s between data."start" and data."end"
                               or d.e between data."start" and data."end"
                                );
--Operation 1 - Disjoined Result   
create table t1 as select s,e,e-s+1 width from
(
select distinct s,(select min(e) from t where t.e>=t1.s) e from t t1
) t2 where t2.s is not null and t2.e is not null;

--Operation 2 - Reduced Result
create table t2 as 
select s,e,e-s+1 width from
(
select s,(select min(d2.e) from t1 d2 where d2.s>=d.s and not exists
          (select s from t1 where t1.s=d2.e+1) ) e
from
t1 d where not exists(select s from t1 where t1.e=d.s-1) 
) t2;

--Temp table for Operation 3 - Gaps
create table t3 as 
select null s, s-1 e from t2
union all
select e+1 s, null e from t2;

现在,这里是查询:

--Operation 1 - Disjoined Result
select * from t1 order by s;

--Operation 2 - Reduced Result


select * from t2 order by s;

--Operation 3 - Gaps

select s,e,e-s+1 width 
from
(
select s,(select min(e) from t3 where t3.e>=d.s) e from t3 d
) t4 where s is not null and e is not null
order by s;


文章来源: Allen's Interval Algebra operations in SQL