Find Consecutive Rows & Calculate Duration
- by MannyKo
I have a set a of data that tells me if a couple of systems are available or not every 5 or 15 minutes increments. For now, the time increment shouldn't matter.
The data looks like this:
Status Time System_ID
T 10:00 S01
T 10:15 S01
F 10:30 S01
F 10:45 S01
F 11:00 S01
T 11:15 S01
T 11:30 S01
F 11:45 S01
F 12:00 S01
F 12:15 S01
T 12:30 S01
F 10:00 S02
F 10:15 S02
F 10:30 S02
F 10:45 S02
F 11:00 S02
T 11:15 S02
T 11:30 S02
I want to create a view that tells when a system is NOT available (i.e. when it is F), from what time, to what time, and duration which is to - from.
Desired results:
System_ID From To Duration
S01 10:30 11:00 00:30
S01 11:45 12:15 00:30
S02 10:00 11:00 01:00
Here is the script data:
DROP SCHEMA IF EXISTS Sys_data CASCADE;
CREATE SCHEMA Sys_data;
CREATE TABLE test_data (
status BOOLEAN,
dTime TIME,
sys_ID VARCHAR(10),
PRIMARY KEY (dTime, sys_ID)
);
INSERT INTO test_data (status, dTime, sys_ID) VALUES (TRUE, '10:00:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (TRUE, '10:15:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '10:30:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '10:45:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '11:00:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (TRUE, '11:15:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (TRUE, '11:30:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '11:45:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '12:00:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '12:15:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (TRUE, '12:30:00', 'S01');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '10:00:00', 'S02');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '10:15:00', 'S02');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '10:30:00', 'S02');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '10:45:00', 'S02');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (FALSE, '11:00:00', 'S02');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (TRUE, '11:15:00', 'S02');
INSERT INTO test_data (status, dTime, sys_ID) VALUES (TRUE, '11:30:00', 'S02');
Thank you in advance!