My problem is simple: I have a table with a series of statuses and timestamps (for the sake of curiosity, these statuses indicate alarm levels) and I would like to query this ta
Finally figured out a version I was happy with. It took me remembering an answer from another question (can't remember which one though) where it was pointed out that the difference between two (increasing) sequences was always a constant.
WITH Ordered (occurredAt, status, row, grp)
as (SELECT occurredAt, status,
ROW_NUMBER() OVER (ORDER BY occurredat),
ROW_NUMBER() OVER (PARTITION BY status
ORDER BY occurredat)
FROM Alert)
SELECT Event.startDate, Ending.occurredAt as endDate,
DATEDIFF(second, Event.startDate, Ending.occurredAt) as interval
FROM (SELECT MIN(occurredAt) as startDate, MAX(row) as ending
FROM Ordered
WHERE status = 2
GROUP BY row - grp) Event
LEFT JOIN (SELECT occurredAt, row
FROM Ordered
WHERE status != 2) Ending
ON Event.ending + 1 = Ending.row
(working SQL Fiddle example, with some additional data rows for work checking).
This unfortunately doesn't correctly deal with level-2 statuses that are end rows (behavior unspecified), although it does list them.