GROUP BY导致SUM()的问题

时间:2016-04-01 16:58:45

标签: mysql sql group-by sum

我正在尝试运行销售报告查询。

我使用SUM()收到的购买总额不正确:似乎问题可能出在我的GROUP BY上。

查询:

SELECT salesreport.canprevid,
  storelist.organization,
  SUM(quantity * unitprice * (100 - discount) / 100) AS total, 
  storelist.external_manager,
  storelist.manager
  FROM storelist
  INNER JOIN salesreport
    ON storelist.store_id = salesreport.canprevid
  WHERE salesreport.date >= "2016-01-01"
    AND salesreport.date <= "2016-01-31"
  GROUP BY canprevid
  ORDER BY organization DESC;

正如所料,我能够拉动:

|canprevid|organization|total (for the month of january 2016)| external manager| manager

然而,当我使用total进行总计SUM()时,total 等于什么2016年1月的真实总金额。

我不确定为什么会删除某些记录或GROUP BY导致计算出现问题。

1 个答案:

答案 0 :(得分:1)

storelist.organization添加到GROUP BY

SELECT salesreport.canprevid,
  storelist.organization,
  SUM(quantity * unitprice * (100 - discount) / 100) AS total, 
  storelist.external_manager,
  storelist.manager
  FROM storelist
  INNER JOIN salesreport
    ON storelist.store_id = salesreport.canprevid 
  WHERE salesreport.date >= "2016-01-01"
    AND salesreport.date <= "2016-01-31"
  GROUP BY salesreport.canprevid, storelist.organization
  ORDER BY storelist.organization DESC;