postgresql postgres内务管理:根据GROUP BY删除旧记录

ncecgwcz  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(175)

我有一张table

agent_audit_log(id, agent_id, api/text, at/timestamp)

目前,我的家政服务

DELETE FROM agent_audit_log WHERE at < NOW()  - INTERVAL '60 days';

而不是上面的内容,我想删除“each”agent_id最新记录超过100条的所有审计日志。我只查到这一点

DELETE FROM agent_audit_log WHERE id NOT IN (SELECT id FROM agent_audit_log ORDER BY at DESC LIMIT 100);

但这需要每一个代理人发生。

e5njpo68

e5njpo681#

问题将是选择正确的id,但您可以使用

CREATE tABLE agent_audit_log(id int, agent_id int , api text, at timestamp)
CREATE TABLE
INSERT INTO agent_audit_log VALUES (1,1,'A',now()), (2,1,'B',now()),(3,2,'A',now()), (4,2,'B',now())
INSERT 0 4
DELETE FROM agent_audit_log 
  WHERE id NOT IN (SELECT MIN(id) FROM agent_audit_log GROUP BY agent_id);
DELETE 2
SELECT * FROM agent_audit_log

| id|代理ID| API|在|
| - -----|- -----|- -----|- -----|
| 1| 1|一个|2023-06-16 22:11:16.919099|
| 3| 2|一个|2023-06-16 22:11:16.919099|

SELECT 2
INSERT INTO agent_audit_log VALUES (2,1,'A',now()), (4,2,'A',now()),(6,1,'A',now()), (6,2,'A',now())
INSERT 0 4
WITH CTE AS (
  SELECT id, ROW_NUMBER() OVER(PARTITION BY agent_id ORDER BY at) rn 
  FROM agent_audit_log)
DELETE FROM agent_audit_log 
  WHERE id NOT IN (SELECT id FROM CTE WHERE rn = 1);
DELETE 4
SELECT *
  FROM agent_audit_log

| id|代理ID| API|在|
| - -----|- -----|- -----|- -----|
| 1| 1|一个|2023-06-16 22:11:16.919099|
| 3| 2|一个|2023-06-16 22:11:16.919099|

SELECT 2

fiddle

相关问题