例如,我有这样的数据
min max time batch sensor
-------------------------------------------------------------------
10 20 2018-07-20 10:15:00:00 x abc
15 30 2018-07-20 10:14:00:00 x abc
15 30 2018-07-20 10:16:00:00 x abc
| | | | | |
| | | | | |
20 30 2018-07-20 11:15:00:00 x abc
现在我想要每小时的数据
min max
------------------------------------------------------------
2018-07-20 10:15:00:00 2018-07-20 11:15:00:00 10 10
答案 0 :(得分:0)
此处的复杂性在于,您每分钟都要检查一个小时范围的窗口,因此,如果要整整一天报告为1,440行。这是一些可以做到的代码:
SET NOCOUNT ON
-- Create a temporary numbers table to demonstrate its use.
-- We need numbers up to 24*60-1 (24 hours * 60 minutes -1 for based on zero)
Declare @DailyIntervals int,
SET @DailyIntervals = 24 * 60 - 1
--SELECT @DailyIntervals
-- This calculates the number of recursive inserts needed to reach at least your maximum value
-- NOTE: This is based off of manually inserting your first four values into the table first!
DECLARE @loop int
SET @loop = CEILING(Log(@DailyIntervals,2))-2
Declare @m int
CREATE TABLE ##Nums (i int primary key clustered);
INSERT INTO ##Nums VALUES (1), (2), (3), (4); -- Seed the table
SET @m = 4
WHILE @loop > 0
BEGIN
INSERT INTO ##nums SELECT I + @m FROM ##Nums
SET @m = @@ROWCOUNT * 2 -- max value in table now
SET @loop = @loop - 1
END
INSERT INTO ##nums Values (0) -- add the zero value
--SELECT MAX(I) FROM ##Nums
-- Look at July 20th
DECLARE @BeginDt datetime = '2018-07-20'
-- Build a working table of one minute intervals for a full day
WITH hhrs as (
SELECT Dateadd(MINUTE, i, @BeginDt) as StartTm,
Dateadd(MINUTE, i+59, @BeginDt) as EndTm
FROM ##Nums
WHERE i BETWEEN 0 and @DailyIntervals
),
SELECT
StartTm,
EndTm,
min([Min]) as [Min],
max([max]) as [Max]
FROM hhrs h
INNER JOIN MyData m
ON m.[Time] Between @StartTm and @EndTm
ORDER BY StartTm
DROP TABLE ##Nums