sql - Postgres选择时间范围之前和之后是否存在另一个事件
问题描述
我有一张这样的桌子:
我需要选择以下记录:
- 所有 A 类
- 仅当在 20 秒之前和之后存在同名的类别 A 时,类别 B
创建测试表:
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');
所以从上面看,这是所需的输出:
解决方案
您可以使用子查询来确定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
)
推荐阅读
- html - 单击 Anchor 标签会产生要跳转的元素
- css - 网页不会呈现指定的字体
- python-3.x - 使用 Pandas 通过分组进行优化
- python - Python 理解 - 投影与过滤的顺序是什么?
- node.js - 使用 ngh 将 Angular 8 项目部署到 Github Pages
- elasticsearch - 从日志消息中提取时间戳
- java - 无法使用 Java 11 通过 jdeps 为遗留 jar 生成模块信息
- python - For 循环将所有值替换为 41
- css - 我的网页上有一个无法摆脱的水平滚动条
- ruby - MongoDB Atlas - Ruby 连接在 Kubernetes 中不起作用