Sql 删除查询以销毁记录组中每个月除最新记录和第一条记录外的所有记录
我想创建一个SQL DELETE查询,该查询在一条语句中删除除以下内容以外的所有内容: 最新记录 除前一个月的第一次记录外,其他所有记录 在一组记录中。我在这里制作了一个SQL fiddle示例: 删除的结果应该是,从组og记录(具有其他_table_id=1)中,只剩下:Sql 删除查询以销毁记录组中每个月除最新记录和第一条记录外的所有记录,sql,postgresql,sql-delete,Sql,Postgresql,Sql Delete,我想创建一个SQL DELETE查询,该查询在一条语句中删除除以下内容以外的所有内容: 最新记录 除前一个月的第一次记录外,其他所有记录 在一组记录中。我在这里制作了一个SQL fiddle示例: 删除的结果应该是,从组og记录(具有其他_table_id=1)中,只剩下: ('2017-01-02', 1), ('2017-03-24', 1), ('2017-04-03', 1), ('2017-05-24', 1), ('2017-12-14', 1) 这可以在一个查询中完成,还是需
('2017-01-02', 1),
('2017-03-24', 1),
('2017-04-03', 1),
('2017-05-24', 1),
('2017-12-14', 1)
这可以在一个查询中完成,还是需要在多个查询中完成?您可以将条件直接转换为delete语句。这里有一种方法:
delete from example_table et
where et.created_at < (select max(et2.created_at) from example_table et2 where et2.other_table_id = et.other_table_id) and
et.created_at not in (select min(et2.created_at) from example_table et2 where et2.other_table_id = et.other_table_id and et2.created_at is not null group by to_char(et2.created_at, 'YYYY-MM'))
还有
编辑:
我明白了。你的问题是上个月。此查询符合您的要求:
delete from example_table et
where et.created_at < (select max(et2.created_at) from example_table et2 where et2.other_table_id = et.other_table_id) and
et.created_at not in (select min(et2.created_at)
from example_table et2
where et2.other_table_id = et.other_table_id and et2.created_at is not null and
date_trunc('month', et2.created_at) <> (select date_trunc('month', max(et3.created_at)) from example_table et3)
group by to_char(et2.created_at, 'YYYY-MM')
);
是SQL小提琴。尝试以下方法:
DELETE FROM example_table
WHERE ID NOT IN(
SELECT ID FROM(
select id
,ROW_NUMBER() OVER(PARTITION BY date_part('year',created_at),date_part('month',created_at) ORDER BY ID)Rn
from example_table WHERE other_table_id =1
)D
WHERE RN=1);
SELECT * FROM example_table;
是我一个人,还是这不管用?我没有看到它删除小提琴中的任何东西:-@NielsKristian。非常感谢。基本问题是,我对相关子查询使用了错误的ID。再次您好,谢谢。现在它在运行。但是,该解决方案与@DineshDB目前建议的解决方案存在相同的问题。它在最近一个月2017-12-10而不是2017-12-14保留了错误记录。这在我创建的第一个种子数据中是不可见的,但是我更新了数据以暴露这一点:事实上,再想想:-现在我正在实现它,我看到了两个缺陷:1。我们需要反转id选择,以避免将其从其他组中删除,其他组为_table_id=2、3和4。2.如果我稍微修改种子数据,我们可以看到第一个标准——最近的记录——实际上没有得到满足。它还保存了最近一个月的第一条记录!在这种情况下,这是2017年12月10日的记录,而不是2017年12月14日的记录。那个我不知道怎么解决的。。。?