简体   繁体   中英

Oracle : How to delete duplicates rows when no distinct value exists?

We have a table with many rows duplicated (2 to 4 times) (each row has the same value for each column). This table has 4 columns but no primary key.

So how to delete the duplicated rows ?

Instance  status  updatetime              name
-----------------------------------------------
gdt546    4       2016/02/13 10:13:18     basic
gdt546    4       2016/02/13 10:13:18     basic
ort87a    1       2016/02/16 19:09:43     High
ort87a    1       2016/02/16 19:09:43     High
ort87a    1       2016/02/16 19:09:43     High

Edited:

The output should be:

 Instance  status  updatetime              name
-----------------------------------------------
gdt546    4       2016/02/13 10:13:18     basic
ort87a    1       2016/02/16 19:09:43     High

Assuming the name of the table is TABLE_NAME and the intent is to delete the duplicate rows such that it retains only one of them, please find the below query:

DELETE FROM table_name A 
WHERE  A.ROWID > ANY (SELECT B.ROWID 
                      FROM   table_name B 
                      WHERE  A.INSTANCE = B.INSTANCE 
                             AND A.status = B.status 
                             AND A.updatetime = B.updatetime 
                             AND A.name = B.name); 

Here you have a solution based on analytic function row_number(). This is the table you want to dedup:

SQL> select * from test1;
INSTANCE|STATUS|UPDATETIME         |NAME    
--------+------+-------------------+--------
gdt546  |     4|2016-02-13 10:13:18|basic   
gdt546  |     4|2016-02-13 10:13:18|basic   
ort87a  |     1|2016-02-16 19:09:43|High    
ort87a  |     1|2016-02-16 19:09:43|High    
ort87a  |     1|2016-02-16 19:09:43|High   

And here you have de-duped rows:

SQL> select instance, status, updatetime, name from 
     ( select row_number() over (partition by instance, status, 
       updatetime, name order by status) as rn, test1.* from test1 ) a
     where a.rn = 1 ;
INSTANCE|STATUS|UPDATETIME         |NAME    
--------+------+-------------------+--------
gdt546  |     4|2016-02-13 10:13:18|basic   
ort87a  |     1|2016-02-16 19:09:43|High    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM