【问题标题】:Perpetual Weighted Average cost Calculation SQL Server 2008永久加权平均成本计算 SQL Server 2008
【发布时间】:2013-01-22 07:22:11
【问题描述】:

我想计算库存的永久加权平均成本。我试图了解以下链接的解决方案 Inventory Average Cost Calculation in 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)

有什么建议吗?

【问题讨论】:

    标签: sql sql-server-2008 aggregate-functions cumulative-sum


    【解决方案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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2014-04-21
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多