2017-04-16 86 views
1

我正在嘗試創建一個TSQL函數來計算庫存計算的加權平均成本。所以給出下面的表結構TSQL加權平均值

ProductId | DatePurchased | Qty | Cost 
--------- | ------------- | --- | ---- 
1   | Jan 1   | 10 | 1.50 
1   | Jan 10  | 5 | 2.00 
1   | Jan 20  | 7 | 2.50 

現在,如果年01月21有人購買15的加權成本將是

((7 * 2.5)+(5 * 2.0)+(3 * 1.5))/ 15 = 2.13

基本上,這是從7月20日,5月從10和從3月1

平均成本我相信這可以用某種遞歸CTE的進行,但由有人比我聰明。

回答

1

一重均是簡單的:

select sum(qty * cost)/sum(qty) 
from t; 

您正在尋找別的東西。也許一個 「分配」 平均:

select sum(case when cume_qty - qty < 15 then qty * cost 
       else (cume_qty - 15) * cost 
      end) as allocated_average 
from (select t.*, 
      sum(qty) over (partition by productid order by date desc) as cume_qty 
     from t 
    ) t 
where cume_qty - qty < 15 and 
     cume_qty >= 15; 
+0

正是基於這裏的描述 http://www.accounting-basics-for-students.com/fifo-method.html – Craig

+0

@Craig。 。 。您正在使用LIFO方法,它似乎與「加權平均」方法不同。 –

+0

你是對的(會計可能不是我的強項)。加權平均值似乎是最不準確的IMO,但這正是客戶想要的。 – Craig