Oracle删除重复数据只保留一条
查询及删除重复记录的SQL语句
1、查找表中多余的重复记录,重复记录是根据单个字段(Id)来判断
select * from 表 where Id in (select Id from 表 group byId having count(Id) > 1)
2、删除表中多余的重复记录,重复记录是根据单个字段(Id)来判断,只留有rowid最小的记录
DELETE from 表 WHERE (id) IN ( SELECT id FROM 表 GROUP BY id HAVING COUNT(id) > 1)
AND ROWID NOT IN (SELECT MIN(ROWID) FROM 表 GROUP BY id HAVING COUNT(*) > 1);
3、查找表中多余的重复记录(多个字段)
select * from 表 a where (a.Id,a.seq) in(select Id,seq from 表 group by Id,seq having count(*) > 1)
4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录
delete from 表 a where (a.Id,a.seq) in (select Id,seq from 表 group by Id,seq having count(*) > 1)
and rowid not in (select min(rowid) from 表 group by Id,seq having count(*)>1)
5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录
select * from 表 a where (a.Id,a.seq) in (select Id,seq from 表 group by Id,seq having count(*) > 1)
and rowid not in (select min(rowid) from 表 group by Id,seq having count(*)>1)
Oracle删除重复记录,保留一条,没有主键的情况
想偷懒,网上搜一个,结果没有找到合适的,自己写个吧。
有主键的比较简单,网上也很多。
--id为主键 a是有重复值的字段
begin
for v in (select a, min(id) id, count(*)
from temp_a
group by a
having count(*) > 1) loop
delete from temp_a t
where t.a = v.a
and t.id <> v.id;
commit;
end loop;
end;
没有主键的话,可以用的通过rowid可以实现。这个网上也很多。思路与主键id一样
--a是有重复值的字段
begin
for v in (select a, min(rowid) id, count(*)
from temp_a
group by a
having count(*) > 1) loop
delete from temp_a t
where t.a = v.a
and t.rowid <> v.id;
commit;
end loop;
end;
刚开始是想通过rownum实现的,发现会有问题,比如:
--a是有重复值的字段,这个sql不会删除任何数据
begin
for v in (select a, count(*) from temp_a group by a having count(*) > 1) loop
delete from temp_a t
where t.a = v.a
and rownum <> 1;
commit;
end loop;
end;
这个是删不了数据的,因为rownum总是从1开始的。第一行不符合的话,第二行的rownum又会成为1。在temp_a表有数据的情况下,下边这个sql查不到任何数据,改成>10也是一样的。而<10可以查到前9条数据。
select * from temp_a where rownum>1;
如果一定想用rownum的话,还有一种做法,就是增加临时列,值等于rownum,这样就相当于有了主键了。
--新增v_id=rownum作为临时主键 a是有重复值的字段
alter table temp_a add v_id number(10);
update temp_a t set t.v_id = rownum;
commit;
begin
for v in (select a, min(v_id) v_id, count(*)
from temp_a
group by a
having count(*) > 1) loop
delete from temp_a t
where t.a = v.a
and t.v_id <> v.v_id;
commit;
end loop;
end;
alter table temp_a drop column v_id;
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。