请求一个SQL的写法

new4everlau 2018-02-08 07:19:48
有一个表,简化如下:包含所有出、入库记录,但是此表的所有出库(InOrOut标记为-1的记录)成本单价全部为空,求一个SQL,完成所有出库成本单价的更新语句。
出库成本单价采用移动加权平均算法。
移动加权平均单价= (本次收入前结存商品金额+本次收入商品金额)/(本次收入前结存商品数量+本次收入商品数量 )
原始记录如下:
InOrOut Date Qty UnitCost Cost
1 2017-09-01 100 23.00 2300.00
1 2017-09-10 400 22.50 9000.00
-1 2017-09-12 300 NULL NULL
1 2017-09-20 200 22.00 4400.00
-1 2017-09-25 300 NULL NULL
1 2017-09-30 333 20.00 6660.00
更新后结果为:
InOrOut Date Qty UnitCost Cost
1 2017-09-01 100 23.00 2300.00
1 2017-09-10 400 22.50 9000.00
-1 2017-09-12 300 A1 B1 --上面2条记录入库,其成本单价为(2300+9000)/(100+400) = 22.6,所以这条的出库成本单价A1 = 22.6,B1 = 300*22.6=6780
1 2017-09-20 200 22.00 4400.00
-1 2017-09-25 300 A2 B2 --此条出库成本单价为:上面结余成本/当前库存,即A2 = (2300+9000-6780+4400)/(100+400-300+200) = 8920/400 = 22.3,B2 = 6690
1 2017-09-30 333 20.00 6660.00
...全文
3391 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_37921165 2018-05-26
  • 打赏
  • 举报
回复
RINK_1 2018-02-09
  • 打赏
  • 举报
回复



if OBJECT_ID(N'tempdb.dbo.#t') is not null
drop table #t
go

create table #t
(InOrOut int,
 io_date date,
 Qty int,
 UnitCost numeric(12,2),
 Cost numeric(12,2))
 
 insert into #t
 select 1,'2017-09-01',100,23,2300 union all
 select 1,'2017-09-10',400,22.5,9000 union all
 select -1,'2017-09-12',300,null,null union all
 select 1,'2017-09-20',200,22,4400 union all
 select -1,'2017-09-25',300,null,null union all
 select 1,'2017-09-30',333,20,6660 UNION ALL
  select -1,'2017-10-30',500,NULL,NULL
 

 with cte_1
 as
 ( select A.*,B.*,ROW_NUMBER() OVER (ORDER BY io_date) as seq 
   from #t A
   outer apply (select SUM(qty) as subtotal_qty,SUM(cost) as subtotal_cost from #t where io_date<A.io_date AND InOrOut=1) AS B
 where InOrOut=-1),
 
 cte_2
 as
 ( select A.*,
          subtotal_cost*1.0/subtotal_qty AS UNITCOST_NEW,
          A.Qty*(subtotal_cost*1.0/subtotal_qty) as cost_NEW,
          -1*A.Qty AS NEXT_QTY,
         -1*A.Qty*(subtotal_cost*1.0/subtotal_qty) AS NEXT_COST
   from cte_1 A
   where seq=1
   union all
   select A.*,
         (NEXT_COST+A.subtotal_cost)*1.0/(B.NEXT_QTY+A.subtotal_qty),
          (NEXT_COST+A.subtotal_cost)*1.0/(B.NEXT_QTY+A.subtotal_qty)*A.QTY,
          B.NEXT_QTY-A.Qty,
          B.NEXT_COST-((NEXT_COST+A.subtotal_cost)*1.0/(B.NEXT_QTY+A.subtotal_qty)*A.QTY)
   from cte_1 A
   join cte_2 B on A.seq=B.seq+1)
                
                
  SELECT * FROM cte_2
  

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧