我有一张表,其中包含可追溯到2年的多种产品的每小时条目。我试图写一个看起来像这样的查询:
PRODUCT, TODAY'S AVERAGE, LAST MONTHS DAILY AVERAGE, YEAR TO DATE DAILY AVERAGE
我能够通过为每个平均值编写单独的查询然后在PRODUCT NAME
上加入它们来实现这一点。但是,我希望能够通过编写一个查询来做同样的事情。
他们是我可以申请的标准算法/方法吗?
答案 0 :(得分:0)
这是一个聚合查询。但是,它会为您想要的每个时间段获取变量,并按天计算以进行最终计算。
select product,
sum(DailySum*IsToday) as Today,
sum(1.0*DailySum*IslastMonth) / sum(IslastMonth)
sum(1.0*DailySum*IsYTD) / sum(IsYTD)
from (select product, cast(dt as date) as thedate, sum(val) as DailySum
(case when cast(dt as date) = cast(getdate() as date) then 1 else 0 end) as IsToday,
(case when year(dt) = year(dateadd(month, -1, getdate()) and month(dt) = month(dateadd(month, -1, getdate())
then 1 else 0
end) as IslastMonth,
(case when year(dt) = year(getdate()) tehn 1 else 0
end) as IsYTD
from t
group by product, cast(dt as date)
) t
) t