对于给定列的每个值,限制为10个最新行

时间:2014-10-24 11:43:55

标签: sql postgresql sql-delete

假设我有以下表结构:

create table foo.bar(
  id serial primary key,
  nema character varying(128) not null,
  cat int not null default 0,
  _date timestamp default default current_timestamp
);

我每天用大量数据填写这张表,我会保留最新的10张相同猫值的记录。
例如,我有5k行,其中100行有cat0xa007,现在我想保留最新的10条记录并删除其余的90行,如下所示:

delete foo.bar f where f.cat=(x'a007'::integer) and f.id not in (
  select b.id from foo.bar b where b.cat=(x'a007'::integer)
  order by b._date desc limit 10 offset 0)

但上述仅适用于一个类别,我如何查询所有类别(所有值)?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

delete from foo.bar where id in
(
select id from 
    ( select id, rank() over (partition by cat order by _date ) ranking from foo.bar) A
    where ranking > 10
)