我有一个表 Department_history ,这是每个部门的记录数。
select department_name, Id, count(1) total_rows_COUNT from Department_history
where
group by Department_history,id
order by 2 desc
结果:
department_name ID total_rows_COUNT
Accounting 4564 556
Finance 3434 671
Marketing 4353 234
IT 1233 454
我只想保留表中每个部门的 10 条记录。
如果像这样为每个部门运行下面的查询,它就可以工作。
delete from Department_history a1
where
and a1.report_runtime NOT IN
(
select report_runtime
from (
select a.*, rank() over ( partition by department_name, id order by report_runtime desc) r
from Department_history a
) rs
where r <= 10 and department_name = 'Accounting'
)
and department_name = 'Accounting'
但我不想为每个部门单独运行此删除操作。如何运行一个查询来删除每个部门名称的数据(如果它是 >10 条记录)。我试试这个。但它不起作用。
delete from Department_history a1
where
and a1.report_runtime NOT IN
(
select report_runtime
from (
select a.*, rank() over ( partition by department_name, id order by report_runtime desc) r
from Department_history a
) rs
where r <= 10
)
有人可以建议吗?