22,207
社区成员
发帖
与我相关
我的任务
分享
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