我有一个子季节,每年都有avg水库流入pr(从1-365开始)。现在,我想在一个新专栏中计算一年中每一天的平滑/移动平均值。
示例:对于1月1日(DayOfYear = 1),我想计算平均21天(10天前和10天后)的平滑度。即平均每天(356-11)。对于55年的某一天,平均值应按一年中的天数(45-65)计算。
她是基于名为' sub'的子查询的未完成查询。其中10年的流入量首先在一年中的平均值;
DECLARE @Dager int ;
SET @Dager = 10; /* # days pre and post the actual day of year to be included in avg */
Select sub.Magasin, sub.DayOfYear, AVG(sub.Inflow) as AvgInflow
FROM (SELECT Date, Magasin, Datepart(dy,Date) as DayOfYear, Value as Inflow
FROM inputtable
WHERE Date >= DATEFROMPARTS(2008,1,1) and Date <= DATEFROMPARTS(2017,12,31)) sub
GROUP By sub.Magasin, sub.DayOfYear
ORDER BY sub.magasin, sub.DayOfYear
答案 0 :(得分:3)
没有任何样本数据,我将为SQL Server 2012 +
建议这样做(您的SQL看起来像SQL Server 2012 +)
SELECT
Magasin,
Datepart(dy,Date) AS DayOfYear,
AVG(Inflow) OVER (
PARTITION BY Magasin
ORDER BY YEAR(Date), Datepart(dy,Date)
ROWS BETWEEN 10 PRECEDING AND 10 FOLLOWING)
FROM
inputtable
WHERE
Date >= DATEFROMPARTS(2008,1,1) and Date <= DATEFROMPARTS(2017,12,31))