我创建了一个仓库库存报告页面。我正在尝试计算我们仓库中每件商品的平均价格。我们每次购买的物品都有不同的价格和数量。例如。我们以每瓶 2 美元的价格购买了 10 瓶水,但下次我们可能会以每瓶 3 美元的价格购买 20 瓶水。
数量 | 单价 | 总计 |
---|---|---|
10 | 2 | 20 |
20 | 3 | 60 |
平均瓶数为 80 瓶 / 30 瓶 = 2.66 美元
但是如果我们从 20 瓶中转移 8 瓶
数量 | 单价 | 总计 |
---|---|---|
10 | 2 | 20 |
12 | 3 | 36 |
现在瓶子的平均值为 56 瓶 / 22 瓶 = 2.54 美元
我想要得到这个的查询是
SELECT
`inventory`.`name` AS `item_name`,
`items`.`brand`,
ROUND (AVG(stockreceive_trans.price), 2) AS price,
`categories`.`name` AS `category_name`,
items.measure_unit,
inventory.barcode,
inv_quantity
FROM `inventory`
JOIN `items` ON inventory.barcode = items.barcode
JOIN `categories` ON inventory.category_id = categories.id
JOIN `stockreceive_trans` ON items.id = stockreceive_trans.item_id
WHERE inventory.warehouse_id = '$warehouse_id'
GROUP BY items.id
但我不知道如何做到这一点。任何帮助深表感谢。预先感谢。
您的问题不完整,因为不要共享其他表格信息。 根据您当前的表格:
数量 | 单价 | 总计 |
---|---|---|
10 | 2 | 20 |
20 | 3 | 60 |
信息解决方案是:
CREATE TABLE T (quantity int, unit_price int, total int);
INSERT INTO T (quantity , unit_price , total ) VALUES
( 10, 2, 20 ),
( 20, 3, 60 );
-- ==============
select
round(sum(total)/sum(quantity), 2) as avg_bottles_price,
round(sum(quantity*unit_price)/sum(quantity), 2) as avg_bottles_price_alternative
from T;
我希望问题能解决您的问题。
谢谢你!!!