【发布时间】:2021-06-28 17:36:07
【问题描述】:
我有下表:
create table foobar (
account_id bigint not null,
timestamp timestamp not null,
balance_one numeric not null,
balance_two numeric not null,
primary key (timestamp, account_id)
);
我有一个给定的时间范围,BEGIN 和 END。在该范围内,以给定步长生成一系列时间戳,从下限开始。我们将这些时间戳称为“间隔边界”。
我想选择给定时间范围内的所有行,其时间戳比任何其他都更接近系列中生成的时间戳之一。
查询的一般部分非常简单,选择给定时间范围内的行:
select * from foobar
where account_id = ?
and timestamp between {BEGIN} and {END}
order by timestamp asc;
我不明白的部分是如何将我的结果集修剪为仅最接近区间边界的行。
示例数据:
| account_id | timestamp | balance_one | balance_two |
|---|---|---|---|
| 1 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
| 1 | 28 June 2021 17:00:05 | 1.0 | 0.0 |
| 1 | 28 June 2021 17:00:10 | 0.5 | 0.0 |
| 1 | 28 June 2021 17:00:15 | 0.0 | 1.0 |
| 1 | 28 June 2021 17:00:20 | 0.5 | 0.0 |
| 1 | 28 June 2021 17:00:25 | 1.0 | 1.0 |
| 2 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
| 2 | 28 June 2021 17:00:05 | 1.0 | 7.0 |
| 2 | 28 June 2021 17:00:07 | 2.0 | 6.0 |
| 2 | 28 June 2021 17:00:15 | 3.0 | 5.0 |
| 2 | 28 June 2021 17:00:20 | 4.0 | 4.0 |
| 2 | 28 June 2021 17:00:25 | 5.0 | 3.0 |
| 2 | 28 June 2021 17:00:30 | 6.0 | 2.0 |
| 2 | 28 June 2021 17:00:35 | 7.0 | 1.0 |
带参数的示例查询:
ID = 1,BEGIN = 2021 年 6 月 28 日 17:00:00,END = 2021 年 6 月 28 日 17:00:30,INTERVAL = 10 秒
结果:
| account_id | timestamp | balance_one | balance_two |
|---|---|---|---|
| 1 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
| 1 | 28 June 2021 17:00:10 | 0.5 | 0.0 |
| 1 | 28 June 2021 17:00:20 | 0.5 | 0.0 |
| 1 | 28 June 2021 17:00:25 | 1.0 | 1.0 |
ID = 2,BEGIN = 2021 年 6 月 28 日 17:00:00,END = 2021 年 6 月 28 日 17:00:30,INTERVAL = 10 秒 结果:
| account_id | timestamp | balance_one | balance_two |
|---|---|---|---|
| 2 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
| 2 | 28 June 2021 17:00:10 | 2.0 | 6.0 |
| 2 | 28 June 2021 17:00:20 | 4.0 | 4.0 |
| 2 | 28 June 2021 17:00:30 | 6.0 | 2.0 |
【问题讨论】:
-
“最接近区间边界”是什么意思?样本数据、期望的结果会有所帮助——清晰的解释也会有所帮助。
-
从任何起始时间戳说
0,以5的间隔递增,我想要时间戳最接近间隔时间戳的记录 -
我冒昧地改写您的问题描述。如果我没有做对,请纠正。
标签: sql postgresql