I've been using a table User Defined Function that takes the requested day in argument, and a cursor inside the function allowing to populate the returned table, as follows :
CREATE TABLE sensor (id int not null identity(1,1) primary key,
measureDate datetime, sensor nvarchar(10), measure float)
INSERT sensor (measureDate, sensor, measure) VALUES
('2015-09-01 09:10', 'T1', '3.2'), ('2015-09-01 09:15', 'T1', '5.2'),
('2015-09-01 09:20', 'T1', '6.2'), ('2015-09-01 09:25', 'T1', '5.8'),
('2015-09-01 09:30', 'T1', '3.2'), ('2015-09-01 09:35', 'T1', '1.2'),
('2015-09-01 09:40', 'T1', '5.6'), ('2015-09-01 09:45', 'T1', '6.1'),
('2015-09-01 09:50', 'T1', '5.0'), ('2015-09-01 09:55', 'T1', '2.0')
GO
CREATE FUNCTION [dbo].[getTimeSpansBelowMaxTemp] (@measureDate date)
RETURNS @timeSpans TABLE (fromTime time, toTime time) AS BEGIN
DECLARE @measure float, @currentMeasure float = NULL
DECLARE @measureTime time, @fromMeasureTime time, @toMeasureTime time
DECLARE yourCursor CURSOR FOR
SELECT CAST(measureDate AS time), measure
FROM sensor
WHERE CAST(measureDate as date) = @measureDate
OPEN yourCursor
FETCH NEXT FROM yourCursor INTO @measureTime, @measure
WHILE (@@FETCH_STATUS = 0) BEGIN -- Loops on all the measures of the given day
IF @measure >= 5.0 BEGIN
IF @currentMeasure IS NULL BEGIN -- Start of a period
SET @currentMeasure = @measure
SET @fromMeasureTime = @measureTime
END
SET @toMeasureTime = @measureTime
END
ELSE BEGIN
IF @currentMeasure IS NOT NULL BEGIN -- End of a period
INSERT INTO @timeSpans VALUES (@fromMeasureTime, @toMeasureTime)
SET @currentMeasure = NULL
END
END
FETCH NEXT FROM yourCursor INTO @measureTime, @measure
END
CLOSE yourCursor
DEALLOCATE yourCursor
RETURN
END
GO
select * from dbo.[getTimeSpansBelowMaxTemp]('2015-09-01')