(PostgreSQL 8.4) I got a great introduction to SQL clearances and islands here in Stack Overflow , but I still have a question, Many CTE island detections are based on the current timestamp order and some flag that breaks the sequence when it changes. But what if the “break” condition is a little more complicated?
CREATE TABLE T1 ( id SERIAL PRIMARY KEY, val INT, -- some device status INT -- 0=OFF, 1=ON ); INSERT INTO T1 (val, status) VALUES (10, 1); INSERT INTO T1 (val, status) VALUES (10, 0); INSERT INTO T1 (val, status) VALUES (11, 1); INSERT INTO T1 (val, status) VALUES (11, 1); INSERT INTO T1 (val, status) VALUES (10, 0); INSERT INTO T1 (val, status) VALUES (12, 1); INSERT INTO T1 (val, status) VALUES (13, 1); INSERT INTO T1 (val, status) VALUES (13, 0); INSERT INTO T1 (val, status) VALUES (13, 1);
In this case, val is a device, and status is either ON or OFF . I want to select records 1 , 3 , 6 , 7 and 9 with the following logic.
10 will turn on - OK, a new sequence, turn on in SELECT
10 disconnects - ends the sequence correctly, ignores the line
11 will turn on - OK, a new sequence, turn on in SELECT
11 turns on - duplicates, ignores the line
10 is turned off - # 10 is not turned on, ignored
12 turns on - OK, implicitly turns off # 11, turns on in SELECT
13 turns on - OK, implicitly turns off # 12, turns on in SELECT
13 turns off - ends the sequence correctly, ignores the line
13 turns on - OK, the new sequence is included in SELECT
In principle, only one device can be turned on at a time, and the break condition is as follows:
- new.val = running.val AND new.status = 0
- new.val <> running.val AND new.status = 1
I am looking for something in the form of a CTE, without cursors.