你可以这样做:
select
b.name,
@av_cost := (select sum(x0.qt*x0.cost)/sum(x0.qt) from buy x0 where x0.name=b.name) as av_cost,
@nr_buy := (select sum(x1.qt) from buy x1 where x1.name=b.name) as nr_buy,
@nr_sold := (select sum(x2.qt) from sell x2 where x2.name=b.name) as nr_sold,
@in_stock := @nr_buy - @nr_sold as in_stock,
@in_stock * @av_cost as value_in_stock
from buy b
group by 1
我相信有人可以优化它,但现在它可以工作。
有关工作示例,请参见Sql fiddle 。
顺便说一句,您在这里使用的是普通演员模型。如果您的所有产品都已售出,并且您以 500 美元的价格购买了新产品,那么该数量的库存不在库存中,因为您过去可能有不同的价格。
如果这不是您想要的,您需要查看“先进先出”系统。在那里,您最后 20 块手表的价格为 20*700,因为您最后 50 块手表每块的价格为 700。
编辑:只有总数
如果您只想要总数,您当然可以这样做:
select sum(x.value_in_stock) as value_total
from (
select
b.name,
@av_cost := (select sum(x0.qt*x0.cost)/sum(x0.qt) from buy x0 where x0.name=b.name) as av_cost,
@nr_buy := (select sum(x1.qt) from buy x1 where x1.name=b.name) as nr_buy,
@nr_sold := (select sum(x2.qt) from sell x2 where x2.name=b.name) as nr_sold,
@in_stock := @nr_buy - @nr_sold as in_stock,
@in_stock * @av_cost as value_in_stock
from buy b
group by 1
) x