在 PostgreSQL 中将时间线数据中的拆分数据分组为一个
Group split data in timeline data in to one in PostgreSQL
我有如下所示的数据。
stationName
status
startTime
endTime
A
normal
09:00
09:10
A
normal
09:10
09:20
B
normal
09:30
09:40
A
normal
09:30
09:40
B
normal
09:40
09:45
A
warning
09:40
09:45
B
warning
09:45
09:55
A
alert
09:45
09:55
B
normal
09:55
10:05
A
alert
09:55
10:05
B
normal
10:05
10:15
A
normal
10:05
10:15
B
normal
10:15
10:25
A
normal
10:15
10:25
B
normal
10:25
10:35
A
normal
10:25
10:35
我想查询数据到这个结构
stationName
status
startTime
endTime
A
normal
09:00
09:40
A
warning
09:40
09:45
A
alert
09:45
10:05
A
normal
10:05
10:35
B
normal
09:30
09:45
B
warning
09:45
09:55
B
normal
09:55
10:35
我的数据时间线数据被分成了很多部分,但我想把它归为一个。
demo
思路:构造一个范围,测试(startTime,endTime)是否属于一个特定的timestamptz范围,
然后按站名,状态,范围(开始时间,结束时间)所属分组。
我会为 startTime、endTime、tstzrange 使用 timestamptz 类型。
如果你构造timerange,那么range (23:00,0:00)
是无效的。
table结构:
CREATE TABLE test102 (
stationName text,
status text,
startTime timestamptz,
endTime timestamptz
);
接着查询:
WITH cte AS (
SELECT
test102.*,
tstzrange(startTime, endTime) tstzrange_se,
tstzrange(i - interval '1 hour', i)
FROM
test102,
generate_series('2022-05-02'::timestamp, '2022-05-02'::timestamp + interval '24 hour', interval '1 hour') i
)
SELECT
stationname,
status,
min(startTime),
max(endTime)
FROM
cte
WHERE
tstzrange_se <@ tstzrange
GROUP BY
1,
2,
tstzrange;
我有如下所示的数据。
stationName | status | startTime | endTime |
---|---|---|---|
A | normal | 09:00 | 09:10 |
A | normal | 09:10 | 09:20 |
B | normal | 09:30 | 09:40 |
A | normal | 09:30 | 09:40 |
B | normal | 09:40 | 09:45 |
A | warning | 09:40 | 09:45 |
B | warning | 09:45 | 09:55 |
A | alert | 09:45 | 09:55 |
B | normal | 09:55 | 10:05 |
A | alert | 09:55 | 10:05 |
B | normal | 10:05 | 10:15 |
A | normal | 10:05 | 10:15 |
B | normal | 10:15 | 10:25 |
A | normal | 10:15 | 10:25 |
B | normal | 10:25 | 10:35 |
A | normal | 10:25 | 10:35 |
我想查询数据到这个结构
stationName | status | startTime | endTime |
---|---|---|---|
A | normal | 09:00 | 09:40 |
A | warning | 09:40 | 09:45 |
A | alert | 09:45 | 10:05 |
A | normal | 10:05 | 10:35 |
B | normal | 09:30 | 09:45 |
B | warning | 09:45 | 09:55 |
B | normal | 09:55 | 10:35 |
我的数据时间线数据被分成了很多部分,但我想把它归为一个。
demo
思路:构造一个范围,测试(startTime,endTime)是否属于一个特定的timestamptz范围,
然后按站名,状态,范围(开始时间,结束时间)所属分组。
我会为 startTime、endTime、tstzrange 使用 timestamptz 类型。
如果你构造timerange,那么range (23:00,0:00)
是无效的。
table结构:
CREATE TABLE test102 (
stationName text,
status text,
startTime timestamptz,
endTime timestamptz
);
接着查询:
WITH cte AS (
SELECT
test102.*,
tstzrange(startTime, endTime) tstzrange_se,
tstzrange(i - interval '1 hour', i)
FROM
test102,
generate_series('2022-05-02'::timestamp, '2022-05-02'::timestamp + interval '24 hour', interval '1 hour') i
)
SELECT
stationname,
status,
min(startTime),
max(endTime)
FROM
cte
WHERE
tstzrange_se <@ tstzrange
GROUP BY
1,
2,
tstzrange;