简体   繁体   中英

Delete rows to have maximum x lines per group in Oracle table

An exemple is the best explanation. Let's say I have the following table : PersonCar (association nxn of persons and cars)

╔════════════╦═════════════╗  
║ PersonId   ║ CarId       ║  
╠════════════╬═════════════╣  
║ 1          ║ 1           ║  
║ 1          ║ 2           ║  
║ 1          ║ 3           ║  
║ 2          ║ 4           ║  
║ 2          ║ 5           ║  
╚════════════╩═════════════╝  

If I group this table by PersonId, the person with Id = 1 have 3 cars associated.
I want to delete rows of the table PersonCar to have maximum 2 cars associated to a person. I don't care about which car is deleted from the association.

It's an exmple. In reality, I have a big test table on which I put too much association (for load tests), and now, I want to clean by putting X association max.

It's an oracle database.

Thank you for your help.

Assuming the combination (person_id, car_id) is unique in the table, you can do something like this:

delete from car_assignment 
where (person_id, car_id) 
        in (select person_id, car_id
            from (
              select person_id, 
                     car_id, 
                     row_number() over (partition by person_id order by car_id) as rn
              from car_assignment
            ) t 
            where rn > 2);

What about trying this way:

Delete from PersonCar
where rowid in ( select row_id
                    from 
                    (
                    select  rowid row_id,    
                           personid , 
                           row_number() over(partition by personid order by personid,carid) rnk       
                    from PersonCar

                    )
                    where rnk >=3 
                 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM