原表
日期 项目 产品名称 变动数量 结存
2022/1/1 A 苹果 20 20
2022/1/3 A 香蕉 50 50
2022/1/5 A 苹果 -10 10
2022/1/6 B 香蕉 20 20
预想效果
日期 项目 产品名称 变动数量 结存
2022/1/1 A 苹果 20 20
2022/1/2 A 苹果 0 20
2022/1/3 A 苹果 0 20
2022/1/3 A 香蕉 50 50
2022/1/4 A 苹果 0 20
2022/1/4 A 香蕉 0 50
2022/1/5 A 苹果 -10 10
2022/1/5 A 香蕉 0 50
2022/1/6 A 苹果 0 10
2022/1/6 A 香蕉 0 50
2022/1/6 B 香蕉 20 20
用with递归可以实现
with t as (
select CAST('01/01/2022' as date) 日期 ,'A' 项目, 'apple' 产品名称, 20 变动数量 ,20 结存 union all
select CAST('01/03/2022' as date) ,'A' , 'banana' 产品名称, 50 变动数量 ,50 结存 union all
select CAST('01/05/2022' as date) ,'A' , 'apple' 产品名称, -10 变动数量 ,10 结存 union all
select CAST('01/06/2022' as date) ,'B' , 'banana' 产品名称, 20 变动数量 ,20 结存
) ,
x as(
select t.*,row_number() over(partition by 项目,产品名称 order by 日期) rn from t) ,
cte as (select 日期,项目,产品名称,变动数量,结存 from x where rn=1
union all
select dateadd(d, 1, cte.日期),cte.项目,cte.产品名称,
isnull((select x.变动数量 from x where dateadd(d, 1, cte.日期)=x.日期 and cte.项目=x.项目 and cte.产品名称=x.产品名称),0),
isnull((select x.结存 from x where dateadd(d, 1, cte.日期)=x.日期 and cte.项目=x.项目 and cte.产品名称=x.产品名称),cte.结存) from cte
where dateadd(d, 1, cte.日期)<=CAST('01/06/2022' as date)
)
select * from cte order by 日期,项目,产品名称
sqlserver的递归sql里不能使用外关联,否则也不需要用子查询来来获取上一行了
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!