sql: Delete oldest n records from each group

孤街醉人 提交于 2019-12-11 18:25:36

问题


I'm using cockroachdb. For each group (grouped by id field), if the number of records exceeds 1000, I want to delete the oldest however_many records so that the number of records equal 1000 after the deletion.

This is what I have so far:

(select id, count(*) - 1000 as num_delete
    from db.table
    group by id
    having count(*) > 1000)

Which gives me the ids for which records will be deleted, as well as the number of records I'll need to delete.

         id | num_delete  
+-----------+------------+
  n7ia6ryc  |        437 

Is there a way, using one sql statement, that I can add to the sql query above so that those records are deleted?


回答1:


I don't know if this works in CockroachDB. If you have a column that is unique, then you can do:

delete from t
    where t.unique_col < (select t2.unique_col
                          from t t2
                          where t2.id = t.id
                          order by t2.unique_col
                          fetch first 1 row only offset 99 rows
                         );

This finds the 100s value of "unique_col" for each id and then deletes all rows (with the same id) that have a smaller value.

If there are not 100 values, then the subquery returns NULL and nothing is deleted.



来源:https://stackoverflow.com/questions/57915714/sql-delete-oldest-n-records-from-each-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!