平均在特定时间内的上周数据

时间:2016-01-29 11:10:49

标签: sql sql-server

我创建了一个sql查询,返回最后一小时的AVG数据。示例:现在是11h,这将返回10h的数据平均值。

现在我需要改进我的查询,我想要同一小时内最后一小时的平均数据和上周所有日子的平均数据。我怎么能这样做?

这是我的疑问:

DECLARE @begin_time smalldatetime,
        @end_time smalldatetime


SET @begin_time = CONVERT(VARCHAR(19), GETDATE(), 120)
SET @begin_time = DateADD(HOUR, -1, @begin_time)
SET @begin_time = convert(char(14),@begin_time,121)+'00:00'


SET @end_time = CONVERT(VARCHAR(19), GETDATE(), 120)
SET @end_time = DateADD(HOUR, -1, @end_time)
SET @end_time = convert(char(14),@end_time,121)+'59:00'

SELECT  u.name,
        YEAR(dpr.reading_time)              AS "year",
        MONTH(dpr.reading_time)             AS "month",
        DAY(dpr.reading_time)               AS "day",
        DATEPART(HOUR, dpr.reading_time)    AS  "hour",
        AVG(CAST(CAST(dpr.value  as DECIMAL(22, 5))/POWER(10, 5) as DECIMAL(20, 5))) * 1 AS "data"

FROM    example.users u                     
        INNER JOIN example.datapoint_readings dpr
        ON dpr.datapoint_id = u.datapoint_id

WHERE   reading_time BETWEEN @begin_time AND @end_time

GROUP BY u.name, YEAR(dpr.reading_time), MONTH(dpr.reading_time), DAY(dpr.reading_time), DATEPART(HOUR, dpr.reading_time)
ORDER BY u.name, YEAR(dpr.reading_time), MONTH(dpr.reading_time), DAY(dpr.reading_time), DATEPART(HOUR, dpr.reading_time)

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望在一段时间内看到每个日期的前一个小时:

SELECT u.name, cast(dpr.reading_time as date) as reading_time_date,
       DATEPART(HOUR, dpr.reading_time) as "hour",
       AVG(CAST(CAST(dpr.value  as DECIMAL(22, 5))/POWER(10, 5) as DECIMAL(20, 5))) * 1 AS "data"
FROM example.users u INNER JOIN
     example.datapoint_readings dpr
     ON dpr.datapoint_id = u.datapoint_id
WHERE datepart(hour, reading_time) = datepart(hour, dateadd(hour, -1, getdate())) AND
      reading_time >= dateadd(day, -7, getdate())
GROUP BY u.name, cast(dpr.reading_time as date),
         DATEPART(HOUR, dpr.reading_time)
ORDER BY u.name,  cast(dpr.reading_time as date),
         DATEPART(HOUR, dpr.reading_time)

重要的区别是WHERE条款。第一个条件提取小时进行比较。第二个将结果限制在过去一周。