我在Oracle数据库中有3个重复的行。只想删除第二条重复记录。我该怎么办?

时间:2019-11-13 14:33:59

标签: sql oracle

示例:

sno Empid Ename Sal
1   100   xxx   1000
2   200   yyy   2000
3   200   yyy   2000
4   200   yyy   2000

EmpidEnamesal是EMP表中的列。 Sno并非专栏,仅用于理解

如何删除第三条记录?

3 个答案:

答案 0 :(得分:0)

这是一种方法:

delete from example e
    where e.sno > (select distinct nth_value(e2.sno, 2) over (partition by e2.empid order by e2.sno)
                   from example e2
                   where e2.empid = e.empid  -- and other columns if necessary
                  );

这是使用nth_value()来获取每位员工的第二个值(如果您希望“重复”表示所有三列,则为其添加条件)。

select distinct使得子查询仅返回一个值。不幸的是,没有nth_value()作为聚合函数。

编辑:

我认为您可以使用rowid

delete from example e
    where e.sno > (select distinct nth_value(e2.rowid, 2) over (partition by e2.empid order by e2.rowid)
                   from example e2
                   where e2.empid = e.empid  -- and other columns if necessary
                  );

答案 1 :(得分:0)

这应该有效:

 DELETE FROM emp 
 WHERE  ROWID = (SELECT Max(ROWID) 
                 FROM (SELECT ROWID, empid 
                       FROM emp 
                       WHERE  empid = 200 
                       ORDER  BY ROWID) 
                 WHERE  ROWNUM <= 2);

答案 2 :(得分:0)

我认为采访者希望您查找具有3个或更多重复项的记录,并从中删除第2个(或重复项中的任何一个)。

尝试一下:

Delete from emp e
Where e.rowid in 
(select rid from 
 ( select t.rowid as rid, 
          Row_number() over (partition by t.empid, t.empno, t.sal order by 1) as rn,
          Count(1) over (partition by t.empid, t.empno, t.sal order by 1) as cnt
    From emp t) 
where cnt >= 3 and rn = 2) -- rn condition is irrelvant here but kept it here for satisfaction of interviewer :)

干杯!