2017-09-11 126 views
1

我有一個KM範圍表和「覆蓋」表的問題。覆蓋的開始和結束可以在表格T1的範圍之間。例如使用postgres覆蓋範圍

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 
+0

什麼是使用 - 案件?我的意思是,你是否真的需要重新計算新的範圍?你不需要根據給定值所屬的範圍(包括覆蓋)來獲得給定值的選項嗎? – Adam

+0

原表只有一公里和一個選項,所以在這一點上選項是有效的。但是Override是從-to開始的,所以我有4.5的差距,因爲我沒有正確的選項。 –

回答

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) 
+0

是的,這是有幫助的,所以我可以減少「幫助1」,並獲得正確的結果返回與我的替換部分http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=d504576dc3521e9435c3ecdf899fa268 –

0

所以從維羅浚的幫助下完成的代碼必須

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;