postgresql - 在 postgres 中,如何找到一个范围内的记录,然后在两侧找到范围外的单个记录?

标签 postgresql datetime range

我在数据库中有一个表,其中包含三个字段:idvaluetimestamp

给定两个日期,我知道如何在 postgres 中编写一个查询,使用 timestamp 字段,将找到一个范围内的所有记录。麻烦的是,我还想找到范围之前最近的单个记录,以及范围之后最近的单个记录。

所以,如果我有这张表:

id | value | timestamp
---+-------+---------------------
 1 |     18| Jan, 1 2017, 09:00:000 
 2 |     16| Jan, 1 2017, 09:05:000
 3 |     14| Jan, 1 2017, 09:21:150
 4 |     12| Jan, 1 2017, 10:01:150
 5 |     13| Jan, 1 2017, 10:07:000
 6 |     09| Jan, 1 2017, 10:23:000

我想写一个包含时间的查询: 2017 年 1 月 1 日,9:10:0002017 年 1 月 1 日,10:05:000

并将返回:

id | value | timestamp
---+-------+---------------------
 2 |     16| Jan, 1 2017, 09:05:000
 3 |     14| Jan, 1 2017, 09:21:150
 4 |     12| Jan, 1 2017, 10:01:150
 5 |     13| Jan, 1 2017, 10:07:000

id 2,是最接近范围底部的记录,但仍然小于范围底部。 id 5,是最接近范围顶部但仍大于(或等于)范围顶部的记录。

最佳答案

使用三个联合:

select * from table where timestamp between start_ts and end_ts
union all
(select * from table where timestamp < start_ts order by timestamp desc limit 1)
union all
(select * from table where timestamp > end_ts order by timestamp limit 1)

所有这些子查询都符合 timestamp 列上的索引。

关于postgresql - 在 postgres 中,如何找到一个范围内的记录,然后在两侧找到范围外的单个记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45723337/

相关文章:

java - 为什么我的数组元素不能被正确解析?

sql-server - Microsoft SQL Server 如何比较查询语句中的 datetime 和 datetimeoffset 值?

JavaScript 正则表达式接受带有逗号分隔符(千)和点分隔符(小数)的数字

ruby-on-rails - 通过连接表查询 Rails 4 Postgres

python - 获取当前日期作为方法的默认参数

vba - 使用事件单元格查找范围名称

python - 如何从Python中的数据帧行中提取特定长度的范围?

python - SqlAlchemy如何将这个类添加到数据库中

postgresql 从两行创建一行

linux - postgresql 服务未在 RHEL 7 上运行