The following query gives you the start and end times of each experiment. It includes the time where the system_on_status
changes back to zero, as this is confirmation the experiment has ended. In the case of the last experiment it has not yet ended (there's no zero for system_on_status
) so the end time is NULL
.
SELECT FromTime = MIN(D.log_date)
,X.ToTime
,D.system_on_status
FROM Experiment_Log D
OUTER APPLY ( SELECT TOP 1
ToTime = D2.log_date
FROM Experiment_Log D2
WHERE D.log_date < D2.log_date
AND D.[system_on_status] <> D2.[system_on_status]
ORDER BY D2.log_date
) X
WHERE D.system_on_status = 1
GROUP BY X.ToTime
,D.system_on_status
ORDER BY FromTime;
Output from this for your data:
FromTime ToTime system_on_status
2014-03-04 16:01:05 2014-03-04 16:01:10 1
2014-03-04 16:01:12 2014-03-04 16:01:16 1
2014-03-04 16:01:19 NULL 1
I can't really claim any glory for this, I took the query from this excellent answer and modified it for your table. So if you want to up-vote go and give ErikE the rep! :)