简体   繁体   中英

Delete older than N days distinct entries

I have to delete data for each Account + date_added combination which is more than N days old. By N days old, it means here deleting older than first N distinct occurrences for above combination

DELETE
FROM tbl_check 
   WHERE
   N  <  (SELECT count(DISTINCT date_added) + 1
   FROM tbl_check b
   WHERE b.ACCOUNT_NUMBER = tbl_check.ACCOUNT_NUMBER
     AND tbl_check.date_added < b.date_added)

This query must run on both Sybase ASE and Oracle. I have written so far above query which is trying to simulate DENSE_RANK and is successfully deleting based on ranking.

However it does not use any index and is also a correlated query doing a FTS. There could be thousands of rows in this table. 在此处输入图片说明

There is a composite PK which is : FOREIGN_KEY_COL , ACCOUNT_NUMBER, date_added , .. Is this query up to the job or we can improve upon it given same query has to work on both databases as mentioned.

为什么不使用以下查询;

DELETE FROM tbl_check  where (getdate()-date_added)> N

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