This is a variation of this question T-SQL Start and end date times from a single column except the event states may have multiple on or off states without a matching opposite state.
The question is how do I capture the start and end dates for the first "on" and next "off". In other words, capture the first COS (change of state) to "on" and the first COS to "off" for each item. This would be used to calculate a total runtime for the item.
Source:
Item EventDate Event
A 2011-10-03 00:01:00 On
A 2011-10-03 00:01:15 On
B 2011-10-03 00:01:00 On
A 2011-10-03 00:02:00 Off
A 2011-10-03 00:02:01 Off
C 2011-10-03 00:01:00 On
B 2011-10-03 00:02:00 Off
A 2011-10-03 00:02:02 On
C 2011-10-03 00:02:05 On
A 2011-10-03 00:02:07 Off
Output:
Item Start End
A 2011-10-03 00:01:00 2011-10-03 00:02:00
A 2011-10-03 00:02:02 2011-10-03 00:02:07
B 2011-10-03 00:01:00 2011-10-03 00:02:00
C 2011-10-03 00:01:00 2011-10-03 00:02:05
If you have SQL Server 2012 or later then you can use SQL Servers windowing function to get the desired results as follow:
Below is an implementation for SQL Server 2008.