使用postgres覆盖范围

时间:2017-09-11 15:35:51

标签: sql postgresql range

我遇到了KM范围表和“覆盖”表的问题。覆盖的开始和结束可以在表T1的范围之间。例如

T1
from    to      option
-1.4    1.7     A
1.7     4.2     B
4.2     4.6     A
4.6     5.3     B

Override
T2
1.2     4.5     C

问题是T1的1.7到4.2行,这条线需要“删除”。 我的上一个版本只能处理两行之间的覆盖,而不是超过3行,我不知道如何解决它。

我在dbfiddle上的最后一个版本: http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=bc71d293c112729fe8d3b077b377ea92

但它应该是:

Result

from    to      option
-1.4    1.2     A
1.2     4.5     C
4.5     4.6     A
4.6     5.3     B

2 个答案:

答案 0 :(得分:1)

我不确定我的问题是否正确。在这里我"删除"从t1开始,t2来自和重叠t1,然后加上t2:

t=# select t1.* from t1
left outer join t2 on t2.fromkm < t1.fromkm and t2.tokm > t1.tokm
where t2.tokm is null
union all
select * from t2
t-# order by fromkm;
 fromkm | tokm | option |  comment
--------+------+--------+------------
   -1.4 |  1.7 | A      | normal
    1.2 |  4.5 | C      | override
    4.2 |  4.6 | A      | normal
    4.6 |  5.3 | B      | normal
(4 rows)

答案 1 :(得分:0)

所以在Vao Tsun的帮助下,完整的代码必须是

with help1 as (
select t1.* from t1
left outer join t2 on t2.fromkm < t1.fromkm and t2.tokm > t1.tokm
where t2.tokm is null
union all
select * from t2
order by fromkm)

,nummer as (
select row_number() over (order by fromkm) as lfdnr,fromkm,tokm,option,comment from help1 )

select 
case when a.fromkm<c.tokm and c.comment='override' then c.tokm else a.fromkm end as fromnew,
case when a.tokm>b.fromkm and a.comment!='override' then b.fromkm else a.tokm end as tonew,
a.option,a.comment from nummer a
left join nummer b on a.lfdnr+1=b.lfdnr
left join nummer c on a.lfdnr=c.lfdnr+1

order by a.fromkm;