根据一年中任何给定时间的标准在 Microsoft SQL Server 中创建未来三到四个月的平均表

问题描述 投票:0回答:1

我需要创建一个表格,它可以根据以下标准为我提供数量信息。有人可以帮助我吗?预先感谢。

现有视图A具有如下所示的信息。请注意,下面只是我的数据示例集。原始数据有2022年12月至2025年12月的信息。

我想计算新数量,在任何给定时间,

Type = S then Quantity = average of Quantity for the next Four months 
(That is, if I am in January my New Quantity for S type items would be (Feb+Mar+Apr+May)/4

Type = P then Quantity = average of Quantity for the next Three months 
(That is, if I am in January my New Quantity for P type items would be (Feb+Mar+Apr)/3

查看 - A :

项目 类型 日期 数量
A S 12/01/2023 100
A S 2024年1月1日 200
A S 2024年2月1日 300
A S 2024年4月1日 400
A S 2024年5月1日 500
B P 12/01/2023 100
B P 2024年1月1日 200
B P 2024年2月1日 300
B P 2024年4月1日 400
B P 2024年5月1日 500
B P 2024年6月1日 600

新的预期输出如下。但是,请注意,我不会看到空白,因为我的数据集确实具有未来几个月的值!

项目 类型 日期 数量 新数量
A S 12/01/2023 100 350 = 1400/4
A S 2024年1月1日 200 0
A S 2024年2月1日 300 `
A S 2024年4月1日 400
A S 2024年5月1日 500
B P 12/01/2023 100 300 = 900/3
B P 2024年1月1日 200 400 = 1200/3
B P 2024年2月1日 300 500 = 1500/3
B P 2024年4月1日 400
B P 2024年5月1日 500
B P 2024年6月1日 600

我尝试为每个月创建单独的列,但这不起作用。

sql-server dataset rolling-average
1个回答
0
投票

您需要将 case 语句与窗口函数一起使用。需要注意的是,如果只剩下两个月,它将计算这两个月的平均值,而不是三或四个月。

-- Creating test table
create table    #test
(
item    varchar(1)
,typ    varchar(1)
,dt     date
,q      int
,new_q  int
)

-- Adding test data
insert into #test (item,typ,dt,q) values
('A', 'S'  ,'12/01/2023', 100)
,('A', 'S' ,'01/01/2024', 200)
,('A', 'S' ,'02/01/2024', 300)
,('A', 'S' ,'04/01/2024', 400)
,('A', 'S' ,'05/01/2024', 500)
,('B', 'P' ,'12/01/2023', 100)
,('B', 'P' ,'01/01/2024', 200)
,('B', 'P' ,'02/01/2024', 300)
,('B', 'P' ,'04/01/2024', 400)
,('B', 'P' ,'05/01/2024', 500)
,('B', 'P' ,'06/01/2024', 600)


select  item    item
        ,typ    typ
        ,dt     dt
        ,q      q
        ,case
            -- calculates average of next four rows with same item and typ (current row not included)
            when typ = 's' then avg(q) over (partition by item, typ order by dt rows between 1 following and 4 following)
            -- calculates average of next three rows with same item and typ (current row not included)
            else avg(q) over (partition by item, typ order by dt rows between 1 following and 3 following)
        end     new_q
from    #test
order by    item
            ,typ
            ,dt


-- Cleaning db
drop table  #test
© www.soinside.com 2019 - 2024. All rights reserved.