Delete all records except the most recent one?

后端 未结 3 1796
渐次进展
渐次进展 2020-12-18 19:07

I have two DB tables in a one-to-many relationship. The data looks like this:

select * from student, application

Resultset:



        
3条回答
  •  感情败类
    2020-12-18 19:45

    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.
    

提交回复
热议问题