我们有一个表,其中有许多行重复(2到4次)(每行对每列都有相同的值)。 此表有4列但没有主键。
那么如何删除重复的行?
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
编辑:
输出应为:
Instance status updatetime name
-----------------------------------------------
gdt546 4 2016/02/13 10:13:18 basic
ort87a 1 2016/02/16 19:09:43 High
答案 0 :(得分:4)
假设表的名称为TABLE_NAME
,并且目的是删除重复的行,使其仅保留其中一个,请查找以下查询:
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);
答案 1 :(得分:0)
这里有一个基于分析函数row_number()的解决方案。这是您要重复删除的表格:
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
在这里你已经删除了行:
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