2016-01-29 44 views
0

我創建了一個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) 
+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條款。第一個條件提取小時進行比較。第二個結果僅限於過去一週。