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.
答案 0 :(得分:0)
这是您的查询:
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;