I have the below table.
time | pid | qty | event
---------------------+------+-----+-------
2021-11-27 16:15:35 | 2207 | 1 | start
2021-11-27 16:15:12 | 2206 | 1 | stop
2021-11-27 16:00:11 | 2207 | 2 | stop
2021-11-27 15:51:43 | 2206 | 1 | start
2021-11-27 15:46:49 | 2206 | 4 | stop
2021-11-27 15:42:47 | 2206 | 4 | start
2021-11-27 15:41:36 | 2206 | 1 | stop
2021-11-27 15:41:29 | 2208 | 3 | start
2021-11-27 15:41:15 | 2207 | 2 | start
2021-11-27 15:39:58 | 2206 | 1 | start
which can be created with:
CREATE TABLE simple (
time TIMESTAMPTZ UNIQUE NOT NULL,
pid BIGINT,
qty BIGINT,
event TEXT
);
INSERT INTO simple VALUES
('2021-11-27 16:15:35' , 2207 , 1 , 'start'),
('2021-11-27 16:15:12' , 2207 , 1 , 'stop '),
('2021-11-27 16:00:11' , 2207 , 2 , 'stop '),
('2021-11-27 15:51:43' , 2206 , 1 , 'start'),
('2021-11-27 15:46:49' , 2206 , 4 , 'stop '),
('2021-11-27 15:42:47' , 2206 , 4 , 'start'),
('2021-11-27 15:41:36' , 2206 , 1 , 'stop' ),
('2021-11-27 15:41:29' , 2208 , 3 , 'start'),
('2021-11-27 15:41:15' , 2207 , 2 , 'start'),
('2021-11-27 15:39:58' , 2206 , 1 , 'start');
At the timestamp of each row, I would like to calculate the minimum qty across all live (non-stopped) start events up until that row, which looks like the below:
time | pid | qty | event | min
---------------------+------+-----+-------+-----
2021-11-27 16:15:35 | 2207 | 1 | start | 1 -- 2207 min pid again
2021-11-27 16:15:12 | 2206 | 1 | stop | 3 -- 2208 min pid, only one not stopped
2021-11-27 16:00:11 | 2207 | 2 | stop | 1
2021-11-27 15:51:43 | 2206 | 1 | start | 1 -- 2206 min pid again
2021-11-27 15:46:49 | 2206 | 4 | stop | 2
2021-11-27 15:42:47 | 2206 | 4 | start | 2
2021-11-27 15:41:36 | 2206 | 1 | stop | 2 -- 2206 stopped, now 2207 is min pid
2021-11-27 15:41:29 | 2208 | 3 | start | 1
2021-11-27 15:41:15 | 2207 | 2 | start | 1 -- min pid is still 2206
2021-11-27 15:39:58 | 2206 | 1 | start | 1 -- first
I've tried a variety of approaches and it seems like my best bet is to define a custom aggregating function, though I lack the technical expertise to do so. Any helpful pointers are welcome!