CREATE TABLE test_tab (
col_name VARCHAR2(20),
log_time TIMESTAMP(6),
status VARCHAR2(20)
);
INSERT INTO test_tab VALUES('Engineering','08-06-22 08:09:16.366000000 PM','UP');
INSERT INTO test_tab VALUES('Engineering','09-06-22 08:28:16.366000000 PM','UP');
INSERT INTO test_tab VALUES('Engineering','09-06-22 08:13:16.366000000 PM','DOWN');
INSERT INTO test_tab VALUES('Commerce','07-06-22 4:59:16.366000000 PM','DOWN');
INSERT INTO test_tab VALUES('Commerce','07-06-22 6:34:16.366000000 PM','UP');
INSERT INTO test_tab VALUES('Commerce','07-06-22 6:49:16.366000000 PM','DOWN');
INSERT INTO test_tab VALUES('Commerce','01-06-22 2:15:16.366000000 PM','UP');
INSERT INTO test_tab VALUES('Commerce','07-06-22 07:04:16.366000000 PM','UP');
COMMIT;
Tool used: SQL Developer(18c)
This is the dataset wherein
- I need to filter based on the
status = 'DOWN'I will get 3 rows which will be my master data. - For the above 3 rows I need to check in the same table i.e
test_tabwith the filterstatus = 'UP'and find the log time which is just greater than the log time of statusDOWN
My Attempt:
WITH a AS(
SELECT col_name, log_time AS start_time, status
FROM test_tab
WHERE status = 'DOWN'),
b AS(
SELECT col_name,log_time AS end_time, status
FROM test_tab
WHERE status = 'UP')
SELECT a.col_name, a.start_time,a.status,
b.end_time,b.status
FROM a
JOIN b ON(a.col_name = b.col_name)
WHERE a.start_time < b.end_time;
But from the above query I am getting duplicate records for col_name = 'Commerce' and giving me the 4 rows in my result but ideally it should be only 3 rows based on the filter DOWN.
Expected Output:
Col_name start_time status end_time status
Engineering 09-06-22 8:13:16.366000000 PM DOWN 09-06-22 8:28:16.366000000 PM UP
Commerce 07-06-22 4:59:16.366000000 PM DOWN 07-06-22 6:34:16.366000000 PM UP
Commerce 07-06-22 6:49:16.366000000 PM DOWN 07-06-22 7:04:16.366000000 PM UP