根据条件postgresql查找以前的值

时间:2018-05-16 11:14:05

标签: sql postgresql postgresql-8.4

a 111
b 567
c 956
d 222
i 492

我想过滤其差异(金额)小于5的唯一ID(按帐户分组)。答案如下:

id    account   amount  
123     abc      10        
1234    abc      12        
4568    abc      16        
456     def      20        
458     def      30         

1 个答案:

答案 0 :(得分:1)

您可以合并LEADLAG以获得所需的结果。

SELECT id
FROM (
    SELECT t.*
        ,amount - LAG(amount, 1, 0) OVER (
            PARTITION BY account ORDER BY amount
            ) AS diff1
        ,amount - LEAD(amount, 1, 0) OVER (
            PARTITION BY account ORDER BY amount
            ) AS diff2
    FROM t
    ) s
WHERE abs(diff1) < 5
    OR abs(diff2) < 5;

Demo