查找重复的行记录并更新另一列

时间:2013-02-07 14:45:20

标签: sql duplicates

我有下表:

Destination     Last Result
(555) 319-5170  Disconnect
(555) 319-5170  Duplicate
(555) 319-5170  Duplicate
(555) 261-5000  Duplicate
(555) 261-5000  Duplicate
(555) 261-7325  Busy
(555) 261-7325  Duplicate

我想找到所有重复的Destination(Phone numbers),并为所有匹配的电话号码更新“最后结果”列,其值不等于“重复”。因此,在上面的目的地((555)319-5170)的示例表中,所有匹配电话号码(555)319-5170)的结果值为“Disconnect”。我的查询如下,但我收到了错误。

update Call
set [last result] = (
select [last result] 
from Call
 WHERE Destination in (select destination from Call group by destination having count(*)>1) and [Last result] != 'Duplicate' and [Last result] != 'No Phone #')
 WHERE Destination in (select destination from Call group by destination having count(*)>1) and [Last result] != 'Duplicate' and [Last result] != 'No Phone #'

Destination     Last Result - EXPECTED OUTPUT
(555) 319-5170  Disconnect
(555) 319-5170  Disconnect
(555) 319-5170  Disconnect
(555) 261-5000  Duplicate
(555) 261-5000  Duplicate
(555) 261-7325  Busy
(555) 261-7325  Busy

提前感谢您寻求可能解决方案的任何帮助。

2 个答案:

答案 0 :(得分:0)

您的子查询返回多个结果,这就是您获得异常的原因。

此查询应该适合您(如果我已正确理解您的标准):

UPDATE C
SET [Last Result] = 'Disconnect'
FROM Call C
INNER JOIN
        (
            SELECT Destination
            FROM Call
            WHERE [Last Result] NOT IN ('Duplicate','No Phone #')
            GROUP BY Destination
            HAVING COUNT(*) > 1
        ) Dup ON Dup.Destination = C.Destination
WHERE C.[Last Result] NOT IN ('Duplicate','No Phone #')

答案 1 :(得分:0)

我对JBond312的答案进行了一些小改动,

UPDATE C
SET [Last Result] = 'Disconnect'
FROM Call C
INNER JOIN
        (
            SELECT Destination
            FROM Call
            WHERE [Last Result] NOT IN ('Duplicate','No Phone #')
            GROUP BY Destination
            HAVING COUNT(Destination) > 1
        ) Dup ON Dup.Destination = C.Destination
WHERE C.[Last Result] NOT IN ('Duplicate','No Phone #')