Postgres选择在时间范围前后是否存在另一个事件

时间:2019-02-26 13:18:42

标签: sql postgresql

我有一张这样的桌子:

enter image description here

我需要选择以下记录:

  • 所有A类
  • 类别B仅在20秒之前和之后存在具有相同名称的类别A

创建测试表:

     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');

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

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用exists子查询来确定20秒内是否存在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
        )

答案 1 :(得分:0)

您可以使用exists。但是您也可以使用窗口功能:

select t.*
from (select t.*,
             max(t.time) filter (t.category = 'A') over (partition by name order by time) as prev_a,
             min(t.time) filter (t.category = 'A') over (partition by name order by time desc) as next_a
      from test t
     ) t
where category = 'A' or
      (category = 'B' and
       (prev_a > time - interval '20 second' or
        next_a < time + interval '20 second'
       )
      );