计算每个月过去 12 个月的平均值?
Posted
技术标签:
【中文标题】计算每个月过去 12 个月的平均值?【英文标题】:Calculate the average of the last 12 months for every month? 【发布时间】:2020-03-27 09:12:15 【问题描述】:我有一个带有值的 SQL 服务器表:
CREATE TABLE [dbo].[MonthleyAvarage](
[Boxes] [int] NULL,
[DateMonthly] [date] NULL
) ON [PRIMARY]
GO
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (1,'01/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (10,'02/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (5,'03/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (9,'04/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (3,'05/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (7,'06/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (5,'07/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (4,'08/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (55,'09/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (6,'10/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (8,'11/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (0,'12/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (2,'01/01/2011')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (1,'02/01/2011')
我试图计算每个月过去 12 个月的平均值,但我只计算了过去 12 个月的累积平均值
select AVG(Boxes) over (order by DATEADD(MONTH, DATEDIFF(MONTH, 0, DateMonthly), -12)) as avarage,DateMonthly,Boxes
from monthleyavarage
我怎样才能只用过去 12 个月?变成这样:
请问我该怎么做?
【问题讨论】:
【参考方案1】:您可以使用带有适当窗口子句的窗口函数:
select
boxes,
dateMonthly,
avg(boxes)
over(order by dateMonthly rows between 11 preceding and current row) avg_boxes
from monthleyavarage
这会为您提供当月和前 11 个月的平均值。
【讨论】:
以上是关于计算每个月过去 12 个月的平均值?的主要内容,如果未能解决你的问题,请参考以下文章