table1 =项目
table2 =销售
SELECT items.itemcode, items.itemname,
sum(items.totalnoofpcs)-ifnull(sum(sales.qty), 0)as sold
FROM items
LEFT JOIN Sales ON items.itemcode = Sales.itemcode
GROUP BY items.itemcode, items.itemname.
最佳答案
这是您的查询:
SELECT i.itemcode, i.itemname,
sum(i.totalnoofpcs)-coalesce(sum(s.qty), 0)as sold
FROM items i LEFT JOIN
Sales s
ON i.itemcode = s.itemcode
GROUP BY i.itemcode, i.itemname;
假定
itemcode
表中每个items
一行,因此不会影响结果。合理的结论是totalnoofpcs
是原因-听起来不像您希望每次销售加起来的那种变量。因此,使用
sum()
代替max()
或将其包含在group by
键中:SELECT i.itemcode, i.itemname,
(i.totalnoofpcs - coalesce(sum(s.qty), 0)) as sold
FROM items i LEFT JOIN
Sales s
ON i.itemcode = s.itemcode
GROUP BY i.itemcode, i.itemname, i.totalnoofpcs;
关于mysql - mysql以双倍显示结果总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47237503/