我有两张桌子
表1 :(购买)
ID。名称,qt,成本
表2 :(卖出)
id,name,qt,sold
我买东西然后再转售。
例如上面的表1显示:我买了20个帽子,每个300美元,60个手表,每个800美元,然后每个700美元(这意味着每个716.66美元)
然后我将它们作为上面的表2重新出售:18顶帽子和40块手表。
所以我有2顶帽子和10只手表留下了instock
我想要的是向人们展示我的物品价值多少。
所以我有2个帽子意味着2 * 300 = $ 600
我剩下10只手表意味着20 * $ 716.66 = $ 1433.2
总计我有$ 600 + $ 1433.2 = $ 14933.2
我如何从上面的2个表中得到(14933.2)的结果。 这对我来说非常重要所以请帮忙!
答案 0 :(得分:2)
你可以这样做:
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。
B.T.W。你在这里工作的平均演员模型。如果您的所有产品都已售出并且您购买了一个新产品,比如说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