开发者

Group by Time Span in SQL Server 2008

I have this table structure:

ID BIGINT IDENTITY(1,1)
deviceID BIGINT NOT NULL,
entryTime DATETIME2 NOT NULL,
value FLOAT,
PRIMARY KEY (ID),
UNIQUE KEY (deviceID, entryTime)

I have about 15 million rows in this table and I want to fill another table with aggregated data from this table. I want to group this data b开发者_开发知识库y deviceID into "buckets" of size one day and take the min, max, and average of the values for that day. Any idea how I do that?


Something like:

SELECT CONVERT(DATE,entryTime) [Date],
       deviceId,
       MIN(Value) MinValue,
       MAX(Value) MaxValue,
       AVG(Value) AvgValue
FROM YourTable
GROUP BY CONVERT(DATE,entryTime),
         deviceId


You could use Convert(DATE, entryTime) as the select and group by clause, however if you wanted to group by more specific, or less specific time periods you'd use something like:

INSERT INTO NEW_TABLE (deviceID, entryTime, min, max, avg)
SELECT deviceID, 
       DATEPART(yy, entryTime)+DATEPART(mm, entryTime)+DATEPART(dd, entryTime),
       MAX(value), 
       MIN(value), 
       AVG(value)
FROM OLD_TABLE 
       GROUP BY 
       deviceId, 
       DATEPART(yy, entryTime)+DATEPART(mm, entryTime)+DATEPART(dd, entryTime)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜