SQL SERVER 查询删除重复数据

Posted 陋室铭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL SERVER 查询删除重复数据相关的知识,希望对你有一定的参考价值。

查询删除重复数据,只保留一条记录:

1.根据单字段,查询表中该字段重复出现记录:

SELECT * FROM Table
WHERE Parameter IN
(SELECT Parameter FROM Table
GROUP BY Parameter HAVING COUNT(Parameter ) > 1)

分析:
SELECT Parameter FROM Table
GROUP BY Parameter HAVING COUNT(Parameter ) > 1
根据字段分组,查询出表中出现重复(字段数量>1)的字段集

-----------------------------华丽的分割线---------------------------------

2.根据单字段,删除表中该字段重复出现记录,保留最小主键ID

DELETE FROM Table
WHERE Parameter IN
(SELECT Parameter FROM Table
GROUP BY Parameter HAVING COUNT(Parameter) > 1)
AND ID NOT IN
(SELECT MIN(ID) FROM Table
GROUP BY Parameter HAVING COUNT(Parameter)>1)


-----------------------------华丽的分割线---------------------------------

3.根据多个字段查询表中重复的记录

SELECT * FROM Table a
WHERE EXISTS
(SELECT Para1 ,Para2 FROM Table b
WHERE a.Para1 = b.Para1 AND
a.Para1 = b.Para2 GROUP BY Para1 ,Para2
HAVING COUNT(*) > 1 )

-----------------------------华丽的分割线---------------------------------

4.根据多个字段 删除表中重复的记录,保留最小主键记录

DELETE A
FROM Table A ,
(SELECT Para1,Para2 FROM Table
GROUP BY Para1,Para2
HAVING COUNT(*) > 1 ) B
WHERE A.Para1=B.Para1 AND a.Para2= b.Para2
AND A.ID NOT IN (SELECT MIN(ID) AS ID
FROM Table
GROUP BY Para1,Para2
HAVING COUNT(*) > 1)

-----------------------------华丽的分割线---------------------------------

5.查询多个字段重复记录,不包含最小主键ID

SELECT * FROM Table a
WHERE EXISTS
(SELECT Para1,Para2 FROM Table b
WHERE a.Para1 = b.Para1 AND a. Para2 = b.Para2
GROUP BY Para1,Para2
HAVING COUNT(*) > 1)
AND ID NOT IN
(SELECT MIN(ID) FROM Table
GROUP BY Para1,Para2
HAVING COUNT(*)>1)

-----------------------------华丽的分割线---------------------------------

以上是关于SQL SERVER 查询删除重复数据的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server 一列或多列重复数据的查询,删除

sqlserver 数据有重复怎么删除

使用sql server 怎么查重复数据

mysql,sqlserver数据库去重

在SQL Server中快速删除重复记录

求教sqlserver排除颠倒重复的数据只保留1条