テーブル 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'
しかし、この削除を部門ごとに個別に実行したくありません。各 department_name のデータを削除する 1 つのクエリを実行するにはどうすればよいですか (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
)
誰かアドバイスしてもらえますか?