我有一张这样的桌子:
我需要选择以下记录:
创建测试表:
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');
因此,从上面看,这是所需的输出:
答案 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'
)
);