我有2个表:stock_material_details和stock_consumed有一个共同的item_id。 stock_material详细信息将added_quantity作为列添加,stock_consumed为consume_quantity作为列。
每次将物品添加到库存中时,它都会添加到stock_material_details(table)中的added_quantity下。
每次消耗一个项目时,它将被添加到comsumed_quantity下的stock_consumed中 我想编写一个查询来获取特定项目的总可用数量,如下所示:
select sum(a.added_quantity ) - sum(b.quantity_consumed) as available
from stock_material_details a
join stock_consumed b on a.item_id = b.item_id
group by a.id
上面的查询所以没有给出多行数据的正确结果。需要一些建议。
答案 0 :(得分:0)
选择item_id,sum(a.added_quantity) - sum(b.quantity_consumed)可从stock_material_details获得a.item_id = b.item_id组中的连接stock_consumed b由a.item_id
尝试添加" item_id"在选择。
我尝试在那里使用你的代码,但它不起作用。
试试这个:
选择item_id,SUM(added_quantity) - (从stock_consumed b中选择SUM(quantity_consumed),其中b.item_id = item_id)FROM stock_material_details group by item_id
希望它有效,因为我只是在脑海里编译它
愿部队与你同在答案 1 :(得分:0)
要混合两个不同的聚合,你需要子查询:
SELECT sum(a.sum_a) - sum(b.sum_b) AS available FROM
(SELECT a.item_id, sum(a.added_quantity ) AS sum_a
FROM stock_material_details a
GROUP BY a.id) AS a
JOIN
(SELECT b.item_id, sum(b.quantity_consumed) AS sum_b
FROM stock_consumed b
GROUP BY b.id) AS b
ON a.item_id = b.item_id
答案 2 :(得分:0)
如果您没有跟踪结果中的每个项目,则无法确定数字对应的内容:
select a.item_id, sum(a.added_quantity ) - sum(b.quantity_consumed) as available
from stock_material_details a
join stock_consumed b on a.item_id = b.item_id
group by a.id