SQLServer删除重复数据保留一条

·

SQLServer删除重复数据保留一条

假设SQLServer数据库中的表(table)名是#tb,表中至少有三列 ID、Name 、EnName等。

创建测试数据:

--创建测试表 #tb
if not object_id('Tempdb..#tb') is null
    drop table #tb
Go

Create table tb([ID] int, [Name] nvarchar(50), [EnName] nvarchar(50))
Insert #tb
select 1,N'NameA',N'EnNameA1' union all
select 2,N'NameA',N'EnNameA2' union all
select 3,N'NameA',N'EnNameA1' union all
select 4,N'NameB',N'EnNameB1' union all
select 5,N'NameB',N'EnNameB2'
Go

 

方法一、

1、查询出重复的数据,Id只保留其中一个

SELECT MIN(ID) ID,Name FROM dbo.#tb 
GROUP BY Name
HAVING COUNT(1) >  1

2、然后使用删除时Join上面的表

DELETE T FROM dbo.#tb T 
JOIN (
    SELECT MIN(ID) ID,Name FROM dbo.#tb
    GROUP BY Name
    HAVING COUNT(1) >  1
) TMP ON T.Name = TMP.Name AND T.Id <> TMP.Id

 

--Name相同ID不同,保留ID最小的一条记录

delete from #tb T where ID not in (select min(ID) from #tb where Name=T.Name)

 

方法二、

1.查询单列重复:

select * from dbo.#tb
where name in (select name from #tb group by name having count(name) > 1)

2.查询多列重复

SELECT T.* FROM  dbo.#tb T,(SELECT Name,EnName FROM #tb GROUP BY Name,EnName HAVING COUNT(1)>1) AS b
WHERE T.name=b.name AND T.code=b.code

 

                

 

 

···········

高级功能请参考(保留最大ID或最小ID):https://www.cnblogs.com/05-hust/articles/14653134.html

 

posted @ 2021-07-07 11:04  亟待!  阅读(2189)  评论(0编辑  收藏  举报
……