1

我在 PostgreSQL 的 TimescaleDB 中工作。我有下表:

| id |      timestamp      |
----------------------------
| 1  | 2021-07-12 01:04:58 |
| 2  | 2021-07-12 02:12:03 |
| 3  | 2021-07-12 04:44:11 |
| 4  | 2021-07-12 05:08:31 |

我可以在一个查询中选择时间戳为 timestamp_start 和时间戳加一小时作为 timestamp_end 的一小时存储桶中的时间(意味着没有子查询)吗?

所以这就是我正在寻找的结果:

|   timestamp_start   |    timestamp_end    |
---------------------------------------------
| 2021-07-12 01:00:00 | 2021-07-12 02:00:00 |
| 2021-07-12 02:00:00 | 2021-07-12 03:00:00 |
| 2021-07-12 03:00:00 | 2021-07-12 04:00:00 |
| 2021-07-12 04:00:00 | 2021-07-12 05:00:00 |
| 2021-07-12 05:00:00 | 2021-07-12 06:00:00 |
4

2 回答 2

2

使用date_trunc,例如

SELECT 
  date_trunc('hour',tm) AS timstamp_start, 
  date_trunc('hour',tm) + interval '1 hour' AS timstamp_end
FROM t;

   timstamp_start    |    timstamp_end     
---------------------+---------------------
 2021-07-12 01:00:00 | 2021-07-12 02:00:00
 2021-07-12 02:00:00 | 2021-07-12 03:00:00
 2021-07-12 04:00:00 | 2021-07-12 05:00:00
 2021-07-12 05:00:00 | 2021-07-12 06:00:00
(4 rows)

演示:db<>fiddle

于 2021-07-12T13:39:43.647 回答
0

它有效,您可以声明如下date_trunc

tsdb=> select time_bucket('1 hour', time) as start, time_bucket('1 hour', time) + interval '1 hour' as end_date from conditions limit 1;
┌────────────────────────┬────────────────────────┐
│         start          │        end_date        │
├────────────────────────┼────────────────────────┤
│ 2010-01-06 22:00:00+00 │ 2010-01-06 23:00:00+00 │
└────────────────────────┴────────────────────────┘
于 2021-07-12T18:02:07.270 回答