首页 > 解决方案 > Postgres选择时间范围之前和之后是否存在另一个事件

问题描述

我有一张这样的桌子:

在此处输入图像描述

我需要选择以下记录:

创建测试表:

     CREATE TABLE test(
       time TIMESTAMP,
       name CHAR(10),
       category CHAR(50)
    );

INSERT INTO test (time, name, category)
    VALUES ('2019-02-25 18:30:10', 'john', 'A'),
           ('2019-02-25 18:30:15', 'john', 'B'),
           ('2019-02-25 19:00:00', 'phil', 'A'),
           ('2019-02-25 20:00:00', 'tim', 'A'),
           ('2019-02-25 21:00:00', 'tim', 'B'),
           ('2019-02-25 21:00:00', 'frank', 'B');

所以从上面看,这是所需的输出:

在此处输入图像描述

标签: sqlpostgresql

解决方案


您可以使用子查询来确定20 秒内exists是否有行:A

select  *
from    test t1
where   category = 'A'
        or exists
        (
        select  *
        from    test t2
        where   t2.category = 'A'
                and t2.name = t1.name
                and abs(extract(epoch from t2.time - t1.time)) < 20
        )

推荐阅读