---
title: "Oracle 中去除重复数据"
author: "zdk8105"
date: "2016-01-07T16:32:56Z"
tags: ["Oracle"]
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2016-01-07T16:32:56Z"
id: 2269240
url: "https://zdk8105.iteye.com/blog/2269240"
---

在网上查了一下，去除重复数据有两种情况：

1、部分字段重复，对于这种情况可这样做：

 

（1）create table 临时表 as select a.字段1,a.字段2,MAX(a.ROWID) dataid from 正式表 a GROUP BY a.字段1,a.字段2; 
（2）　delete from 表名 a 
　　  where a.rowid != 
　  　( 
　　  select b.dataid from 临时表 b 
　  　where a.字段1 = b.字段1 and 
　　  a.字段2 = b.字段2 
　　  );

（3）commit;

 

我不想删除原有数据，就另建了一个表：

（1）create table 临时表 as select a.字段1,a.字段2,MAX(a.ROWID) dataid from 正式表 a GROUP BY a.字段1,a.字段2;

（2）create table 去重表名 as select  a.*  from 正式表  a, 临时表 b  where a.rowid = b.dataid;

 

 

 

2.对于完全重复的数据，网上说可以这样：

　（1）　CREATE TABLE 临时表 AS (select distinct * from 表名);

　（2）　truncate table 正式表;

　（3）   insert into 正式表 (select * from 临时表);

　（4）   drop table 临时表;

从SQL语句来看，应该是可以实现的。

 

 

 

更新：

对于不完全重复数据还找到了以下方法，利用ORACLE中的ROWID：

假设student表中的stunum字段中有重复数据，现在要找出哪些数据重复，并删除。

 

查看哪些数据重复：

 

select * from student where stunum in (select stunum(select stunum ,count(*) from student group by stunum having count(*) >1))  --这句太复杂，要好好想想怎么简化。

 

select * from student a,student b where a.stunum = b.stunum and a.rowid < b.rowid

 

 

 

删除重复数据：

 

delete from student a where a.rowid<(select max(rowid) from student b where a.stunum = b.stunum)