我有返回小时数据的查询。但是我想从该查询中获取每日数据,因此每天的所有每小时数据都将平均为每日数据。
declare @Days int
set @Days = -1
select
dateadd(hour,datepart(hour,Timestamp),cast(CAST((Timestamp) as date) as datetime)) as [Time]
,[value]
from [Employee]
where dateadd(hour,datepart(hour,Timestamp),cast(CAST((Timestamp) as date) as datetime)) >= CONVERT(date, DATEADD(DAY, @Days, GETDATE()))
答案 0 :(得分:1)
假设您要对其他列进行平均和按日期分组,则可以尝试以下操作:
DECLARE @Days int = -1;
SELECT
CAST(Timestamp AS date) AS date
, AVG(Value) AS Value
FROM [Employee]
WHERE Timestamp >= DATEADD(day, @Days, CAST(GETDATE() AS date))
GROUP BY CAST(Timestamp AS date)
ORDER BY date;
请注意,重构的WHERE
子句避免将函数应用于列值。这样可以有效地使用Timestamp
上的索引(可表达)。