在SQL Server 2012中计算移动平均

时间:2019-05-21 04:57:28

标签: sql sql-server-2012 forecasting moving-average

我需要计算移动平均线。

我可以使用Alteryx来获得此功能,但是不能使用SQL来获得所需的结果。

基本上我已经设置了周期值。

该值可用于6个期间,我想通过移动平均值来预测下一个值。

例如

Period     Value
01-04-2016 4
01-05-2016 5
01-06-2016 6

对于2016年1月7日,它将是(4 + 5 + 6)/ 3 = 5

以及下一个值

Period     Value
01-05-2016 5
01-06-2016 6
01-07-2016 5

对于2016年1月8日,它将是(5 + 6 + 5)/ 3 = 5.33333。

(6 + 5 + 5.333)/ 3 = 5.44444

(5 + 5.3333 + 5.4444)= 5.259259

以此类推。

下表3MonthForecast中的预期结果。

CREATE TABLE [dbo].[MovingAvg]
(
    [Period] [date] NULL,
    [Value] [float] NULL,
    [3MonthForecast] [float] NULL
) 

INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-01-01' AS Date),  1, 1)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-02-01' AS Date),  2, 2)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-03-01' AS Date),  3, 3)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-04-01' AS Date),  4, 4)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-05-01' AS Date),  5, 5)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-06-01' AS Date),  6, 6)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-07-01' AS Date), null, 5)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-08-01' AS Date), null, 5.333333333)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-09-01' AS Date), null, 5.444444444)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-10-01' AS Date), null, 5.259259259)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-11-01' AS Date), null, 5.345679012)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2016-12-01' AS Date), null, 5.349794239)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2017-01-01' AS Date), null, 5.31824417)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2017-02-01' AS Date), null, 5.337905807)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2017-03-01' AS Date), null, 5.335314739)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2017-04-01' AS Date), null, 5.330488239)
GO
INSERT [dbo].[MovingAvg] ([Period], [Value], [3MonthForecast]) VALUES (CAST(N'2017-05-01' AS Date), null, 5.334569595)

1 个答案:

答案 0 :(得分:2)

我们可以尝试使用AVG作为分析函数,并在适当的窗口中获取前面的三个记录:

SELECT 
    [Period],
    [Value],
    [3MonthForecast],
    AVG([3MonthForecast]) OVER (ORDER BY [Period] ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING) AS MovingAvgForecast
FROM [dbo].[MovingAvg]
ORDER BY
    [Period];

Demo