问题
I want to calculate Perpetual Weighted Average cost for inventory. I tried to understand a solution on following link Inventory Average Cost Calculation in SQL but cannot get it, it is complex for me.
here is my database details.
Purch_ID Item_ID QTY Unit_Price
01 1 10 10
02 2 10 20
03 3 20 15
04 2 10 20
05 1 10 18
06 2 25 17
I want to calculate the Weighted Average cost after each Purchase using following formula
((old_stock x Old unit price)+(New_Purchase_qty x New unit price))/(old stock qty + new purchase qty)
any suggestions please ?
回答1:
If I understand correctly, you want the cumulative average price.
This approach uses subqueries to calculate the cumulative total quantity and the cumulative total paid. The ratio is the avg cost:
select t.*, cumepaid / cumeqty as avg_cost
from (select t.*,
(select SUM(qty) from t t2 where t2.item_id = t.item_id and t2.purch_id <= t.purch_id
) as cumeqty,
(select SUM(qty*unit_price) from t t2 where t2.item_id = t.item_id and t2.purch_id <= t.purch_id
) as cumepaid
from t
) t
In SQL Server 2012, you can do this by directly calculating cumulative sums (should be more efficient). You could also do this with cross apply
, but I prefer standard SQL.
来源:https://stackoverflow.com/questions/14740181/perpetual-weighted-average-cost-calculation-sql-server-2008