我一直在使用一個表用戶定義的函數該參數需要一天的時間,並且該函數中的光標允許填充返回的表格,如下所示:
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')
如果您可以提供一些示例數據以及所需的結果集,將會有所幫助。 –
我不確定從哪裏開始。我想我必須找到所有記錄值> = 5,然後我必須找到最後一個記錄,其中值大於等於5,但是其中沒有任何記錄與情人值。 –
如果我們認爲它是一個溫度傳感器,並且它每5分鐘記錄一次。 tabel會是這樣的。 1. 2015.09.01 09:10 T1 3,2 2. 2015.09.01 09:15 T1 5,2 3. 2015.09.01 09:20 T1 6,2 4. 2015.09.01 09:25 T1 5 ,8 5. 2015.09.01 09:30 T1 3,2 6. 2015.09.01 09:35 T1 1,2 7. 2015.09.01 09:40 T1 5,6 8. 2015.09.01 09:45 T1 6,1 9. 2015.09.01 09:50 T1 5,0 10. 2015.09。01 09:55 T1 2,0 我試圖找到的periodes然後是從09:15到09:25和從09:40到09:50。 –