简体   繁体   中英

SQLITE 3 - Delete older than N instances per item

I have a table with the RUN_TIME and OPERATION_NAME columns. I'd like to trim the table by deleting older than N instances of each operation. For example: If the input table is

RUN                 OPERATION
13/11/2012 05:39    GAM010P0
14/11/2012 05:39    GAM010P0
15/11/2012 05:39    GAM010P0
13/11/2012 05:09    GAM020P0
14/11/2012 05:09    GAM020P0
15/11/2012 05:09    GAM020P0
16/11/2012 05:09    GAM020P0
01/11/2012 17:09    GAM060P0

And I'd like to maintain 2 most recent instances of each operation, the output would be:

RUN                 OPERATION
14/11/2012 05:39    GAM010P0
15/11/2012 05:39    GAM010P0
15/11/2012 05:09    GAM020P0
16/11/2012 05:09    GAM020P0
01/11/2012 17:09    GAM060P0

Normally I'd use the RANK analytical function to rank by RUN_TIME and group by OPERATION_NAME; however since this table exists on sqlite DB, I am not able to write a delete SQL statement to achieve this.

You have to count how many records for the same operation exist in the database. If, for a particular record, there are two or more other records with a timestamp that is newer, then this record should be deleted:

DELETE FROM MyTable
WHERE (SELECT COUNT(*)
       FROM MyTable AS Newer
       WHERE Newer.OPERATION = MyTable.OPERATION AND
             Newer.RUN > MyTable.RUN
      ) >= 2

Please not that you have to use a date format like yyyy-mm-dd with the most significant field at the beginning so that the date comparisons work.

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