删除表中的多个重复行

2021-09-10 00:00:00 sql tsql sql-server

我在一个表中有多组重复项(一个表有 3 条记录,另一个表有 2 条记录,等等)- 存在多于 1 条记录的多行.

I have multiple groups of duplicates in one table (3 records for one, 2 for another, etc) - multiple rows where more than 1 exists.

以下是我想删除它们的方法,但是无论有多少重复项,我都必须运行脚本:

Below is what I came up with to delete them, but I have to run the script for however many duplicates there are:

set rowcount 1
delete from Table
where code in (
  select code from Table 
  group by code
  having (count(code) > 1)
)
set rowcount 0

这在一定程度上效果很好.我需要为每组重复项运行它,然后它只删除 1 个(这是我现在需要的全部).

This works well to a degree. I need to run this for every group of duplicates, and then it only deletes 1 (which is all I need right now).

推荐答案

如果您在表中有一个键列,那么您可以使用它来唯一标识表中的不同"行.

If you have a key column on the table, then you can use this to uniquely identify the "distinct" rows in your table.

只需使用子查询来识别唯一行的 ID 列表,然后删除该集合之外的所有内容.类似......的东西

Just use a sub query to identify a list of ID's for unique rows and then delete everything outside of this set. Something along the lines of.....

create table #TempTable
(
    ID int identity(1,1) not null primary key,
    SomeData varchar(100) not null
)

insert into #TempTable(SomeData) values('someData1')
insert into #TempTable(SomeData) values('someData1')
insert into #TempTable(SomeData) values('someData2')
insert into #TempTable(SomeData) values('someData2')
insert into #TempTable(SomeData) values('someData2')
insert into #TempTable(SomeData) values('someData3')
insert into #TempTable(SomeData) values('someData4')

select * from #TempTable

--Records to be deleted
SELECT ID
FROM #TempTable
WHERE ID NOT IN
(
    select MAX(ID)
    from #TempTable
    group by SomeData
)

--Delete them
DELETE
FROM #TempTable
WHERE ID NOT IN
(
    select MAX(ID)
    from #TempTable
    group by SomeData
)

--Final Result Set
select * from #TempTable

drop table #TempTable;

或者,您可以使用 CTE,例如:

Alternatively you could use a CTE for example:

WITH UniqueRecords AS
(
    select MAX(ID) AS ID
    from #TempTable
    group by SomeData
)
DELETE A
FROM #TempTable A
    LEFT outer join UniqueRecords B on
        A.ID = B.ID
WHERE B.ID IS NULL

相关文章