Oracle更新表中的重复行

时间:2012-02-07 10:30:29

标签: c# sql oracle

我有一个名为users的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) ;

但这似乎没有我想要的。我做错了什么?

2 个答案:

答案 0 :(得分: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比较是为了防止与自己匹配的拖链!)

答案 1 :(得分: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;