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)
請編輯您的問題,並提供樣本數據和預期結果。 –