Oracle更新表中的identic行

时间:2012-02-02 09:54:28

标签: sql oracle odp.net

我有一个名为users的表,其中包含以下列:

Name, Location, Active (all varchars).
John    Berlin  OK
Danny   London  OK
Robert  NY      OK
John    Berlin  OK
Danny   Berlin  OK

对于出现多次(两次,三次或x次)的用户,我想将Active列更新为NOK - 并且它们具有相同的名称和位置(表中的相同行)如下所示:

    John    Berlin  NOK
    Danny   London  OK
    Robert  NY      OK
    John    Berlin  NOK
    Danny   Berlin  OK

我该怎么做? 谢谢!

2 个答案:

答案 0 :(得分:2)

在Oracle中,您可以使用:

UPDATE your_table
   SET active = 'NOK'
 WHERE (name, location) IN (SELECT name, location 
                              FROM your_table 
                             GROUP BY name, location 
                            HAVING COUNT(*) > 1)

答案 1 :(得分:0)

你需要这样做:

将重复值插入#temp表

select t.Name, t.Location
into #test
from tablename t
group by t.Name, t.Location
having count(t.Name) > 1

进行更新

update tablename
set Active = 'NOK'
from tablename t
inner join #test t2 on t.Name = t2.Name and t.Location = t2.Location

或者一步到位:

update tablename
set Active = 'NOK'
from tablename t
inner join (select t.Name, t.Location
            from tablename t
            group by t.Name, t.Location
            having count(t.Name) > 1) t2 on t.Name = t2.Name and t.Location = t2.Location