oracle 查询及删除表中重复数据

create table test1(
id number,
name varchar2(20)
);

  

insert into test1 values(1,'jack');
insert into test1 values(2,'jack');
insert into test1 values(3,'peter');
insert into test1 values(4,'red');

 insert into test1 values(5,'green');
  insert into test1 values(6,'green');

oracle 查询及删除表中重复数据

一 查询表中重复数据

1. 使用exists

 select a.* from test1 a

 where exists

 (
select name from
( select name ,count(*)
from test1
group by name
having count(*)>1
) b
where a.name = b.name
);

oracle 查询及删除表中重复数据

2 join on

select a. * from test1 a
join (
select name ,count(*) from test1
group by name
having count(*)>1
) b
on a.name = b.name;

oracle 查询及删除表中重复数据

3 in

select a.name from test1 a
where a.name in
(
select name from test1
group by name
having count(*)>1
);

oracle 查询及删除表中重复数据

4 使用rowid 查询得到重复记录里,第一条插入记录后面的记录

select * from test1 a where  rowid != (select min(rowid) from test1 b where b.name = a.name);

  oracle 查询及删除表中重复数据

5 使用rowid查询得到重复记录里,最后一条记录之前插入的记录

select a.* from test1 a where rowid !=(select max(rowid) from test1 b where a.name=b.name);

  oracle 查询及删除表中重复数据

6 使用rowid 查询得到 不重复的记录和重复记录里最后插入的一条记录

select a.* from test1 a where rowid =(select max(rowid) from test1 b where a.name=b.name);

  oracle 查询及删除表中重复数据

7 使用rowid 查询得到不重复的记录和重复记录里最先插入的记录

select * from test1 a where  rowid = (select min(rowid) from test1 b where b.name = a.name);

  oracle 查询及删除表中重复数据

删除  所有重复不保留任何一条

delete  from test1 a where exists ( select name from (select name ,count(*) from test1  group  by name having count(*)>1) b where a.name = b.name);

  

delete from test1 a where a.name in (select name  from test1  group  by name having count(*)>1);

  

删除重复记录里,第一条重复记录后面插入的记录

delete from test1 a where  rowid  !=(select min(rowid) from test1 b where b.name = a.name);

oracle 查询及删除表中重复数据  

删除先前插入的重复记录,保留最后插入的重复记录

delete  from test1 a where rowid !=(select max(rowid) from test1 b where a.name=b.name);

  oracle 查询及删除表中重复数据

上一篇:oracle 查询今天哪个表增加的数据多


下一篇:ORACLE 查询被锁定表及解锁释放session的方法