SQL Server 删除重复记录,只保留一条记录

时间:2022-09-22 23:04:05

原文地址:https://www.cnblogs.com/luodengxiong/p/4997471.html

 

1、查询重复记录:

SELECT * FROM dbo.Table T
WHERE EXISTS (SELECT 字段1, 字段2, 字段3 FROM dbo.TableSign WHERE 字段1= T.字段1 AND 字段2= T.字段2
AND 字段3 = T.字段3 GROUP BY 字段1, 字段2, 字段3 HAVING COUNT(*) > 1)
AND T.SelfID NOT IN (SELECT MIN(SelfID) FROM dbo.Table GROUP BY 字段1, 字段2, 字段3 HAVING COUNT(*) > 1)

--其中:字段1, 字段2, 字段3指需要建立唯一约束的三个字段,SelfID指表Table中的一个自增字段。

2、删除重复记录,只保留SelfID最小的记录,也就是第一次插入的记录:

DELETE FROM dbo.TableSign
WHERE SelfID IN

(SELECT SelfID FROM dbo.Table T

WHERE EXISTS (SELECT 字段1, 字段2, 字段3 FROM dbo.TableSign WHERE 字段1= T.字段1 AND 字段2= T.字段2
AND 字段3 = T.字段3 GROUP BY 字段1, 字段2, 字段3 HAVING COUNT(*) > 1)
AND T.SelfID NOT IN (SELECT MIN(SelfID) FROM dbo.Table GROUP BY 字段1, 字段2, 字段3 HAVING COUNT(*) > 1))