sql中怎么将重复的记录去掉

来源:百度知道 编辑:UC知道 时间:2024/09/27 15:27:00
sql中怎么将重复的记录去掉

方法一按照多条件重复处理:
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(2) from 表
where not exists (select 主键ID
from #tmp where #tmp.主键ID=表.主键ID)

通过临时表
select distinct * into #a from [表名]
delete [表名]
insert into [表名]
select * from #a

table1:
col1 col2
111 lsy
222 cdd
333 ldd
111 lsy

假设col1设置成主键列

sql:delete from table1 where col1 in(select col1 from table1 having count(col1)>2)

select 所有列 from 表名 group by 所有列

这样的话如果所有列相同就会被去掉了

select