删除表中的多个重复行

时间:2023-02-24
本文介绍了删除表中的多个重复行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个表中有多组重复项(一个表有 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

这篇关于删除表中的多个重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在 SQL Server 中分配行号,但按值分组 下一篇:是否可以使用 SQL 将身份添加到 GROUP?

相关文章

最新文章