0

我有一张表,其中包含可追溯到 2 年的多种产品的每小时条目。我正在尝试编写一个看起来像这样的查询:

PRODUCT, TODAY'S AVERAGE, LAST MONTHS DAILY AVERAGE, YEAR TO DATE DAILY AVERAGE

我可以通过为每个平均值编写单独的查询然后将它们加入到PRODUCT NAME. 但是,我希望能够通过编写一个查询来做到这一点。

他们是我可以应用的标准算法/方法吗?

4

1 回答 1

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
于 2012-12-11T23:15:09.857 回答