YHSY1995 2022-02-22 23:45 采纳率: 50%
浏览 64
已结题

用SQLServer 填充缺少日期的不同项目不同产品的每日结存

问题遇到的现象和发生背景

原表
日期 项目 产品名称 变动数量 结存
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

问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

2条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-02-23 13:12
    关注

    用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 日期,项目,产品名称
    

    img

    sqlserver的递归sql里不能使用外关联,否则也不需要用子查询来来获取上一行了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月15日
  • 已采纳回答 4月7日
  • 创建了问题 2月22日