I have a table containing events. Each event has a defined starting and ending timestamp:
start_ts | end_ts |
---|---|
2023-07-27 01:02:00 | 2023-07-27 01:05:00 |
2023-07-27 01:05:00 | 2023-07-27 01:07:00 |
2023-07-27 01:07:00 | 2023-07-27 01:11:00 |
2023-07-27 01:11:00 | 2023-07-27 01:15:00 |
2023-07-27 01:30:00 | 2023-07-27 01:35:00 |
2023-07-27 01:35:00 | 2023-07-27 01:42:00 |
2023-07-27 01:45:00 | 2023-07-27 01:50:00 |
From this structure, I want to find out, active and inactive periods. Active periods are defined by the time range in which an event takes place. Such an active period can be composed of multiple consecutive events. In inactive periods no event is taking place. So the expected output would be like:
period_start | period_end | status |
---|---|---|
2023-07-27 01:02:00 | 2023-07-27 01:15:00 | active |
2023-07-27 01:15:00 | 2023-07-27 01:30:00 | inactive |
2023-07-27 01:30:00 | 2023-07-27 01:42:00 | active |
2023-07-27 01:42:00 | 2023-07-27 01:45:00 | inactive |
2023-07-27 01:45:00 | 2023-07-27 01:50:00 | active |
Any idea how I can achieve this by using PostgreSQL?
CREATE TABLE IF NOT EXISTS events(
id INT PRIMARY KEY,
start_ts timestamp NOT NULL,
end_ts timestamp NOT NULL
);
INSERT INTO events(id,start_ts,end_ts)
VALUES
(1,'2023-07-27 01:02:00','2023-07-27 01:05:00'),
(2,'2023-07-27 01:05:00','2023-07-27 01:07:00'),
(3,'2023-07-27 01:07:00','2023-07-27 01:11:00'),
(4,'2023-07-27 01:11:00','2023-07-27 01:15:00'),
(5,'2023-07-27 01:30:00','2023-07-27 01:35:00'),
(6,'2023-07-27 01:35:00','2023-07-27 01:42:00'),
(7,'2023-07-27 01:45:00','2023-07-27 01:50:00');