1. 程式人生 > >Oracle 中去除重複資料

Oracle 中去除重複資料

在網上查了一下,去除重複資料有兩種情況:

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)

真正實施方案如下:

create table mytable_uni as select distinct * from mytable;

truncate table mytable;

alter table mytable disable all triggers;

insert into mytable select * from mytablebak_QUCH;
commit;

alter table mytable enable all triggers;