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

PostgreSQL如何按person_id取最新2行对比deposit字段是否下降

解决思路

窗口定义语法本身不支持直接加LIMIT限制分组内行数,你可以按以下步骤实现需求:

  1. 先对每个person_id分组内的记录按时间倒序排序,标记行号,仅保留行号≤2的记录,得到每个用户最新的2条数据
  2. 对筛选后的结果集使用LAG函数获取上一条记录的deposit和时间
  3. 最后过滤出前一条deposit大于当前deposit的记录即可

可直接运行的SQL语句

WITH ranked_customer AS (
    SELECT 
        person_id,
        employee_id,
        deposit,
        ts,
        -- 按用户分组,时间倒序排列,最新的记录行号为1
        ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY ts DESC) AS rn
    FROM customer
)
SELECT 
    person_id,
    employee_id,
    deposit,
    ts,
    pre_deposit,
    pre_ts
FROM (
    SELECT 
        *,
        LAG(deposit) OVER (PARTITION BY person_id ORDER BY ts ASC) AS pre_deposit,
        LAG(ts) OVER (PARTITION BY person_id ORDER BY ts ASC) AS pre_ts
    FROM ranked_customer
    WHERE rn <= 2 -- 仅保留每个用户最新2条记录
) t
WHERE pre_deposit > deposit -- 筛选余额下降的记录

说明

针对你的示例数据,该查询会先过滤掉person_id=101的第三条旧记录,仅保留最新的2条,对比后仅返回符合pre_deposit > deposit的结果,和你期望的输出完全一致。


内容的提问来源于stack exchange,提问作者kuzua

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:15:05