我有两个MySQL表,我想使用但不幸的是这个问题超出了我的知识。
第一张表显示了我的产品ID和数量
id PID Quantity
1 5 8
2 45 7
3 125 0
第二个表存储了我购买我库存产品的订单。
id Date PO ID PID Price Purchased Quant.
1 1.1.19 PO1 5 8.00 7
2 1.1.19 PO1 45 2.15 9
3 2.1.19 PO2 5 4.45 6
因此,我想得到每个qazxsw pmi的平均价格,从最近的购买日期算起。
PID
对于PID Average Price
5 5.3375
45 2.15
'5'我有8件库存,我发现6件在2.1.19购买4,45€。因此,我需要在较旧的购买中找到另外2件,我可以在1.1.19找到8.00€。
PID
对于PID 45,计算应该相同,但是我的库存完全满足第一个PO。
有什么办法可以在MySQL中用查询来解决这个问题。
在8.0之前的MySQL版本中,这并不容易实现。您可以使用在执行查询期间更改的变量来执行此操作,但请注意,没有文档保证变量赋值的顺序与预期的一样。
现在我已经给出了免责声明,这是您可以使用的查询:
Average price calculation -> (6pcs * 4.45€ + 2pcs * 8.00€)/8pcs = 5.3375€
select pid,
sum(price * take)/sum(take) avg_price
from (
select pid,
price,
@quantity := if(@pid = pid, @quantity, available) needed,
least(@quantity+0, quantity) take,
@quantity := @quantity - least(@quantity, quantity),
@pid := pid
from (select o.*,
p.quantity available
from orders o
inner join products p
on p.pid = o.pid
order by o.pid,
o.date desc) data,
(select @pid := -1,
@quantity := 0) vars
order by pid, date desc) base
group by pid
为了更可靠的方式,您最好迁移到可以使用窗口函数的MySQL。