如何基于其他查询动态设置SQL语句中的OFFSET参数?
表结构与需求说明
我的表结构如下:
| name | processed | processing | updated | ref_time |
|---|---|---|---|---|
| abc | t | f | 27794395 | 27794160 |
| def | t | f | 27794395 | 27793440 |
| ghi | t | f | 27794395 | 27793440 |
| jkl | f | f | 27794395 | 27794160 |
| mno | t | f | 27794395 | 27793440 |
| pqr | f | t | 27794395 | 27794160 |
已基于此结构创建在线示例环境,无需重复构建。
之前我用以下SQL删除表中的“旧”条目,逻辑是保留所有记录均已processed的最新ref_time,删除其余符合条件的条目:
with ref as ( select ref_time from status_table group by ref_time having bool_and(processed) order by ref_time desc offset 1 ) delete from status_table s using ref r where s.ref_time = r.ref_time
但现在需要更灵活的逻辑:
- 基础逻辑:保留所有记录均已
processed的最新ref_time - 特殊情况:如果第二个最新的
ref_time对应的总记录数(cnt_total)比第一个多,则需要同时保留前两个最新的ref_time
我可以通过以下SQL统计每个ref_time的相关数据:
select ref_time, count(*) cnt_total, count(*) filter(where processed) cnt_processed, round(avg(processed::int),2) ratio_processed from status_table group by ref_time order by ratio_processed desc, ref_time desc;
在当前示例中,ref_time=27794160应该被保留(而非纳入删除列表),因为它是第二个最新的ref_time,且其cnt_total比第一个更高。
核心规则:按ref_time从新到旧的顺序,保留所有条目,直到遇到第一个cnt_total等于或小于前一个ref_time的条目为止(该条目及之后的都删除)。
内容的提问来源于stack exchange,提问作者drmrbrewer
相关产品推荐
相关产品推荐

