Perpetual Weighted Average cost Calculation SQL Server 2008

时光总嘲笑我的痴心妄想 提交于 2019-12-12 02:26:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!