I have two DB tables in a one-to-many relationship. The data looks like this:
select * from student, application
Resultset:
You can use row_number()
(or rank()
or dense_rank()
, or even just the rownum
pseudocolumn) to apply an order to the records, and then use that order to decide which to discard. In this case, ordering by applicationdatetime desc
gives the application with the most recent date for each student the rank of 1:
select studentid, applicationid from (
select studentid, applicationid,
row_number() over (partition by studentid
order by applicationdatetime desc) as rn
from application
)
where rn = 1;
STUDENTID APPLICATIONID
---------- -------------
1 20002
2 20005
You can then delete anything with a rank higher than 1, which will preseve the records you care about:
delete from application
where (studentid, applicationid) in (
select studentid, applicationid from (
select studentid, applicationid,
row_number() over (partition by studentid
order by applicationdatetime desc) as rn
from application
)
where rn > 1
);
3 rows deleted.