删除一组重复记录并保留另一组重复记录

时间:2009-12-18 11:26:39

标签: sql tsql

请参阅下面的数据 alt text http://img709.imageshack.us/img709/1980/deleteduprecords.png

我想保留一组记录,并希望删除另一组重复的记录。你可以看到ForeignKey是相同的只是主键是不同的。

需要在4条记录中保留2条主键最低的记录。

3 个答案:

答案 0 :(得分:2)

Delete from Table mytable t1
where exists (select 1 from mytable t2
where t2.PrimaryKey < t1.PrimaryKey
and t2.ForeignKey = t1.ForeignKey
and t2.AnotherForeignKey = t1.AnotherForeignKey)

答案 1 :(得分:1)

使用SQL Server 2005中的CTE功能,您可以删除重复记录,如下所示

(PS。我看不到设计,所以这是一种方法。)

DECLARE @Table TABLE(
        ID INT,
        FK INT,
        VName VARCHAR(50)
)

INSERT INTO @Table (ID,FK,VName) SELECT 1, 1, 'A'
INSERT INTO @Table (ID,FK,VName) SELECT 2, 1, 'A'
INSERT INTO @Table (ID,FK,VName) SELECT 3, 1, 'A'
INSERT INTO @Table (ID,FK,VName) SELECT 4, 2, 'B'
INSERT INTO @Table (ID,FK,VName) SELECT 5, 2, 'B'
INSERT INTO @Table (ID,FK,VName) SELECT 6, 2, 'B'

;WITH CTE AS (
    SELECT *,
            ROW_NUMBER() OVER (PARTITION BY FK  ORDER BY ID) RowNumber
    FROM    @Table
)
DELETE FROM CTE WHERE RowNumber > 1

SELECT * FROM @Table

答案 2 :(得分:0)

实际上我是一个困境,无论你是用SET来表示所有最后2个字段的组合还是仅仅是外键。

如果它只是外键,请接受Astender的解决方案。

如果是最后两个字段,那么

示例输入:

PK  FK  AFK
4669    121 1
4670    121 2
10675   121 1
10676   121 2
101 254 1
102 254 2
703 254 1
704 254 2

<强>查询:

;with cte as(
select
ROW_NUMBER() over(partition by FK ,AFK order by GETDATE()) rn,
t.* from @t t)
delete from cte where rn = 1
select * from @T

<强>输出:

PK  FK  AFK
4669    121 1
10676   121 2
102 254 2
703 254 1