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)