【问题标题】:Delete Duplicate records using ROWNUM OR ROW_NUMBER IN Oracle在 Oracle 中使用 ROWNUM 或 ROW_NUMBER 删除重复记录
【发布时间】:2021-07-18 05:05:31
【问题描述】:

我有 Oracle 11g。我有 4 条记录,我想使用 ROWNUM 或 ROW_NUMBER 删除重复记录。 表格如下。

id name dept salary
100 nikhil prod 12000
100 nikhil prod 12000
200 john HR 10000
200 john HR 10000

我想要这样的输出

id name dept salary
100 nikhil prod 12000
200 john HR 10000

【问题讨论】:

  • 只需使用CREATE TABLE t2 AS SELECT DISTINCT * FROM t :)
  • 为什么要使用row_number() 而不是select distinct

标签: sql oracle oracle11g


【解决方案1】:

架构和插入语句:

 create table salarytable (id int,  name varchar(50), dept varchar(50), salary  int);

 insert into salarytable values(100 ,'nikhil','prod', 12000 );
 insert into salarytable values(100, 'nikhil', 'prod', 12000); 
 insert into salarytable values(200, 'john', 'HR', 10000); 
 insert into salarytable values(200, 'john', 'HR', 10000);

删除查询:

 DELETE FROM salarytable
 WHERE rowid not in
 (SELECT MIN(rowid)
 FROM salarytable
 GROUP BY id ,name ,dept ,salary);

选择查询:

 select * from salarytable;

输出:

ID NAME DEPT SALARY
100 nikhil prod 12000
200 john HR 10000

db小提琴here

使用 row_number() 删除重复项

使用 row_number() 删除查询:

 delete from salarytable
 where  rowid in
 ( select rwid
   from ( select rowid rwid
          ,      row_number() over ( partition by id order by id) rn
          from   salarytable
        )
   where  rn>1
 )

选择查询:

 select * from salarytable;

输出:

ID NAME DEPT SALARY
100 nikhil prod 12000
200 john HR 10000

db小提琴here

【讨论】:

  • 我想使用 rownum
  • 好的。让我再尝试一次。您使用的是哪个版本的 oracle?
  • 我已经用 row_number() 修改了我的答案
  • 这仅认为 2 行是重复的,如果它们具有相同的 id 值,而它们可能具有相同的 id 和不同的 namedeptsalary,然后可能不能重复。使用ROW_NUMBER() OVER ( PARTITION BY id, name, dept, salary ORDER BY ROWNUM ) 可能会更全面地检查重复项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 2014-03-12
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多