Sql 删除行以使Oracle表中每个组最多有x行
一个例子是最好的解释。 假设我有下表:个人协会n x n个人和汽车Sql 删除行以使Oracle表中每个组最多有x行,sql,oracle,Sql,Oracle,一个例子是最好的解释。 假设我有下表:个人协会n x n个人和汽车 ╔════════════╦═════════════╗ ║ PersonId ║ CarId ║ ╠════════════╬═════════════╣ ║ 1 ║ 1 ║ ║ 1 ║ 2 ║ ║ 1 ║ 3 ║ ║ 2 ║ 4 ║
╔════════════╦═════════════╗
║ PersonId ║ CarId ║
╠════════════╬═════════════╣
║ 1 ║ 1 ║
║ 1 ║ 2 ║
║ 1 ║ 3 ║
║ 2 ║ 4 ║
║ 2 ║ 5 ║
╚════════════╩═════════════╝
如果我按PersonId将此表分组,则Id=1的人有3辆关联的汽车。
我想删除PersonCar表中的行,以使一个人最多有2辆汽车。我不在乎哪辆车被从协会中删除
这是一个例子。事实上,我有一个很大的测试表,我在上面为负载测试放了太多的关联,现在,我想通过放X关联最大值来清理
这是一个oracle数据库
谢谢您的帮助。假设表中的人员id和车辆id组合是唯一的,您可以执行以下操作:
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);
假设组合person\u id和car\u id在表中是唯一的,您可以执行以下操作:
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);
这样试试怎么样:
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
);
这样试试怎么样:
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
);
我试试看,然后回来。我不知道我们可以用元组搜索。很高兴知道。我试试看,然后回来。我不知道我们可以用元组搜索。很高兴知道。