SQL语句去掉重复记录,获取重复记录

 
代码
--按照某几个字段名称查找表中存在这几个字段的重复数据并按照插入的时间先后进行删除,条件取决于order by 和row_num
--
方法一按照多条件重复处理:
delete tmp from(
select row_num = row_number() over(partition by 字段,字段 order by 时间 desc)
    
from 表 where 时间> getdate()-1
) tmp
where row_num > 1 

--方法二按照单一条件进行去重:
delete from 表 where 主键ID not in(
select max(主键ID) from 表 group by 需要去重的字段 having count(需要去重的字段)>=1
)
--注意:为提高效率如上两个方法都可以使用临时表, not in 中的表可以先提取临时表#tmp,
--
然后采用not exists来执行,为避免数量过大,可批量用Top控制删除量
delete top(2from 表 
        
where  not exists (select 主键ID
  
from #tmp where #tmp.主键ID=表.主键ID) 
原文地址:https://www.cnblogs.com/hanguoji/p/470021.html