2012-02-07 43 views
2

我有一個Oracle表稱爲用戶,列甲骨文更新表中的重複行

name, location, organization, valid_from, valid_to, active. 

我所試圖做的是: 如果有兩個記錄具有相同的名稱,地點,組織,但與valid_to,valid_from間隔重疊,以將每個記錄的活動狀態設置爲「NOK」。 以下是我正在試圖做到這一點:

UPDATE table SET active= 'NOK' 
WHERE 
(name, location, organization) IN (
    SELECT t1.name, t1.location, t1.organization 
    FROM table t1 
    WHERE (valid_from > t1.valid_from and valid_to < t1.valid_to) 
     GROUP BY t1.name, t1.location, t1.organization 
     HAVING COUNT(*) > 1) ; 

但是,這似乎並沒有做什麼,我的願望。我究竟做錯了什麼?

回答

4

的WHERE在你的子查詢子句將是FALSE所有行,因爲你沒有某些列指定表的別名:

(valid_from > t1.valid_from and valid_to < t1.valid_to) 

將假設意味着

(t1.valid_from > t1.valid_from and t1.valid_to < t1.valid_to) 

我覺得這你想要做什麼:

UPDATE table t1 SET active = 'NOK' 
WHERE EXISTS 
(SELECT 1 
    FROM table t2 
    WHERE t2.name = t1.name 
    AND t2.location = t1.location 
    AND t2.organization = t1.organization 
    AND t1.valid_from <= t2.valid_to 
    AND t2.valid_from <= t1.valid_to 
    AND t1.ROWID != t2.ROWID 
); 

但是,如果valid_from或valid_to可以爲null,那麼您還需要處理該情況。

(ROWID比較是爲了防止絲束與自己匹配!)

0

試試這個方法:

UPDATE table SET a.active= 'NOK' 
from table a 
inner join (
    SELECT t1.name, t1.location, t1.organization 
    FROM table t1 
    WHERE (valid_from > t1.valid_from and valid_to < t1.valid_to) 
     GROUP BY t1.name, t1.location, t1.organization 
     HAVING COUNT(*) > 1) b 
    on a.name = b.name and a.location = b.location and a.organization = b.organization;