-->

永久加权平均成本计算的SQL Server 2008(Perpetual Weighted Aver

2019-10-28 13:35发布

我想计算永久加权平均成本的存货。 我试图了解在以下链接解决方案在SQL库存平均成本计算 ,但不能得到它,它是复杂的对我。

这里是我的数据库的详细信息。

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      

我想每个计算购买后的加权平均成本使用下列公式

((old_stock x Old unit price)+(New_Purchase_qty x New unit price))/(old stock qty + new purchase qty)

有什么建议吗?

Answer 1:

如果我理解正确的话,你想要的累计平均价格。

这种方法使用子查询来计算累计总数量和支付的累计。 的比率是平均成本:

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

在SQL Server 2012中,您可以通过直接计算累计总和(应该是更有效)做到这一点。 你也可以用做cross apply ,但我更喜欢标准的SQL。



文章来源: Perpetual Weighted Average cost Calculation SQL Server 2008