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
Just for the sake of having an alternative. Tried to do some test on performance, but did not finish.
SELECT
MIN([main].[Start]) AS [Start],
[main].[End],
DATEDIFF(s, MIN([main].[Start]), [main].[End]) AS [Seconds]
FROM
(
SELECT
[sub].[Start],
MIN([sub].[End]) AS [End]
FROM
(
SELECT
[start].[Timestamp] AS [Start],
[start].[Status] AS [StartingStatus],
[end].[Timestamp] AS [End],
[end].[Status] AS [EndingStatus]
FROM [Alerts] [start], [Alerts] [end]
WHERE [start].[Status] = 2
AND [start].[Timestamp] < [end].[Timestamp]
AND [start].[Status] <> [end].[Status]
) AS [sub]
GROUP BY
[sub].[Start],
[sub].[StartingStatus]
) AS [main]
GROUP BY
[main].[End]
And here is a Fiddle.