You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于其他查询动态设置SQL语句中的OFFSET参数?

表结构与需求说明

我的表结构如下:

nameprocessedprocessingupdatedref_time
abctf2779439527794160
deftf2779439527793440
ghitf2779439527793440
jklff2779439527794160
mnotf2779439527793440
pqrft2779439527794160

已基于此结构创建在线示例环境,无需重复构建。

之前我用以下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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:55:21