1、查找重复记录
①如果只是不想在查询结果中存在重复记录, 可以加Distinct
select distinct * from TestTable
②如果是想查询重复的记录及其数量
select UserID,UserName,count(*) as '记录数'
from TestTable
Group by UserID,UserName
having count(*)>1
③ID不重复, 但是字段重复的记录只显示一条
select * from TestTable where UserID in
(select max(UserID) as UserID from TestTable group by UserName,Sex,Place)
2、删除重复记录
①一种思路是利用临时表, 把查询到的无重复记录填充到临时表, 再把临时表的记录填充回原始表
select distinct * into #Temp from TestTable
drop table TestTable
select * into TestTable from #Temp
drop table #Temp
②删除ID不重复, 但是字段重复的记录(就是按字段查询出相同字段记录中最大的ID,然后保留此记录, 删除其他记录).(group by 的字段, 有点麻烦).
delete TestTable where UserID not in
(select max(UserID) as UserID from TestTable group by UserName,Sex,Place)