Example:
sno Empid Ename Sal
1 100 xxx 1000
2 200 yyy 2000
3 200 yyy 2000
4 200 yyy 2000
Empid
,Ename
,sal
are columns in the EMP table. Sno
is not a column,its just for understanding
How to delete 3rd record?
Example:
sno Empid Ename Sal
1 100 xxx 1000
2 200 yyy 2000
3 200 yyy 2000
4 200 yyy 2000
Empid
,Ename
,sal
are columns in the EMP table. Sno
is not a column,its just for understanding
How to delete 3rd record?
Here is one method:
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
);
This is using nth_value()
to get the second value for each employee (if you want "duplicate" to mean all three columns then add conditions for them).
The select distinct
is so the subquery returns only one value. Unfortunately, there is no nth_value()
as an aggregation function.
EDIT:
I think you can use 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
);
This should work:
DELETE FROM emp
WHERE ROWID = (SELECT Max(ROWID)
FROM (SELECT ROWID, empid
FROM emp
WHERE empid = 200
ORDER BY ROWID)
WHERE ROWNUM <= 2);
I think theinterviewer wanted you to find the records which have 3 or more duplicates and delete 2nd (or any from the duplicates) from it.
Try this:
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 :)
Cheers!!