SQL - 将重复行插入新表,然后删除重复记录

时间:2017-08-04 16:07:50

标签: sql sql-server

在我的表中,我需要在另一个表中插入重复的记录。我需要从第一个表中删除它。

我发现的代码是这样的:

WITH q AS 
(
    SELECT a.* FROM SampleData AS a
    LEFT JOIN SampleData AS b ON 
    a.Name = b.Name AND 
    a.Account= b.Account AND
    a.Amount = -b.Amount 
    WHERE b.Name IS NOT NULL
)
DELETE FROM q OUTPUT DELETED.* INTO SampleData2

现在的问题是它返回一个错误:

  

查看或功能' q'不可更新,因为修改会影响多个基表。

对此有何帮助?我无法找到解决此错误的方法。

3 个答案:

答案 0 :(得分:3)

尝试使用EXISTS

WITH q AS 
(
    SELECT a.* 
    FROM SampleData AS a
    WHERE EXISTS (SELECT 1
                  FROM SampleData AS b
                  WHERE  a.Name = b.Name 
                    AND  a.Account= b.Account 
                    AND  a.Amount = -b.Amount)
)
DELETE FROM q OUTPUT DELETED.* INTO SampleData2

答案 1 :(得分:0)

尝试这样......

WITH q
AS (SELECT
        a.*
    FROM
        SampleData AS a
        LEFT JOIN SampleData AS b
            ON a.Name = b.Name
            AND a.Account = b.Account
            AND a.Amount = - b.Amount
    WHERE
        b.Name IS NOT NULL
)
DELETE s
    OUTPUT Deleted.* INTO Sample2
FROM 
    SampleData s
    JOIN q
        ON s.Name = q.Name
        AND s.Account = q.Account;

答案 2 :(得分:0)

我假设下面的CTE选出了重复项:

WITH q AS 
 (
 SELECT a.* FROM SampleData AS a
 LEFT JOIN SampleData AS b ON 
 a.Name = b.Name AND 
 a.Account= b.Account AND
 a.Amount = -b.Amount 
 WHERE b.Name IS NOT NULL
 )

SELECT * INTO NEWTABLE FROM q --Takes duplicates from CTE and inserts into a table called NEWTABLE

DELETE FROM FIRST_TABLE 
WHERE NEWTABLE.Column = FIRST_TABLE.Column --Or whatever matches to help you delete the duplicates

希望这有帮助!