我想创建一个(?=\d).{6,}?
查询,在一个语句中删除除以下内容之外的所有内容:
在一组记录中。我在这里做了一个SQL小提琴示例:http://www.sqlfiddle.com/#!15/2272a
删除的结果应该是,从组og记录(具有SQL DELETE
的记录)中,唯一剩下的应该是:
other_table_id = 1
这一切都可以在一个查询中完成,还是我需要在多个查询中执行?
答案 0 :(得分:2)
试试这个:
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;
答案 1 :(得分:0)
您可以将条件直接转换为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'))
编辑:
我明白了。你的问题是&#34;上个月&#34;。此查询可以执行您想要的操作:
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')
);
Here是SQL小提琴。