我有两个表,如下:
第一个表显示了所有订单:
table PURCHASE_ORDER:
ID UNIT_# PRICE ITEM_KEY
1 2 3 1
2 3 2.5 1
3 1 3 1第二个表显示了库存中的可用数量:
table INVENTORY:
ID ITEM_KEY UNIT_AVAILABLE
1 1 5
2 2 7现在的问题是如何计算库存中物品的平均成本。例如,第1项:
物料1的平均成本= ((1*3)+(3*2.5)+(1*3))/5
/*库存物品总数为5件(1+3+1 =5件) */
有没有办法在纯microsoft SQL中做到这一点?
发布于 2014-01-24 08:20:51
你需要一个累加的总数。假设您使用的是SQL Server 2012,因为它简化了代码。
select po.item_key,
(sum(case when po.cumunits <= i.unit_available then po.[unit#]*po.price
when po.cumunits > i.unit_available and
po.cumunits - [unit#] < i.unit_available
then (i.unit_available - (po.cumunits - [unit#]))*po.price
else 0
end) /
sum(case when po.cumunits <= i.unit_available then po.[unit#]
when po.cumunits > i.unit_available and
po.cumunits - [unit#] < i.unit_available
then (i.unit_available - (po.cumunits - [unit#]))
else 0
end)
) as avgprice
from (select po.*, sum([unit#]) over (partition by item_key order by id) as cumunits
from purchase_order po
) po join
inventory i
on po.item_key = i.item_key
group po.item_key;在SQL Server的早期版本中,需要对累积和使用相关子查询。
https://stackoverflow.com/questions/21321885
复制相似问题