mysql显示结果总和为double

时间:2017-11-11 11:40:20

标签: mysql sql group-by

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. 

1 个答案:

答案 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;