I have a table that is used to log events. Two types specifically : ON and OFF.
There are sometimes overlapping log entries as there can be 2 simultaneous devices logging. This is not crucial, as the end report should give a [mostly] correct overview of ON -> OFF periods.
Below is a sample, with the 3rd column just for illustration: It does not exist.
ActionTaken ID ID_of_next_OFF
Switched ON 1 3
Switched ON 2 6
Switched OFF 3
Switched ON 4 7
Switched ON 5 8
Switched OFF 6
Switched OFF 7
Switched OFF 8
Switched On 9 10
Switched OFF 10
Switched On 11 12
Switched OFF 12
Given the first two columns, how can I calculate the third?
This does not work:
SELECT actionTaken, Id, LEAD(Id)
OVER (PARTITION BY ActionTaken ORDER BY ID) nextConn
FROM dbo.Events
as it bases the ID_of_Next on the next matching actionTaken value, instead of the next alternate.
You are on the right way. All you need is the
LEFT JOIN
of the'Switched ON'
part with the'Switched OFF'
part on equal row numbers.Output:
Test it online with SQL Fiddle.
something like this should get you there.
Below I've used 2 CTE's to split the off and on data and then provide a ranking item for first switch on first switch off then I've used a union query to match those up