SQL 重复记录问题的处理方法小结

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,Place)

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...