Mysql和结果重复

时间:2015-08-09 19:25:55

标签: mysql

我正在尝试使用以下查询获取每天/商店​​的销售总额:

SELECT st.name, SUM(sa.val), sa.sale_date FROM sales sa
  INNER JOIN employee e ON sa.employee_id
INNER JOIN store st ON e.store_id
GROUP BY st.name, sa.sale_date
ORDER BY sa.sale_date

但它会为SUM生成重复的结果。

+---------+-------------+------------------------+
|  name   | SUM(sa.val) |       sale_date        |
+---------+-------------+------------------------+
| Store 1 |         800 | July, 29 2015 00:00:00 |
| Store 2 |         800 | July, 29 2015 00:00:00 |
+---------+-------------+------------------------+

应该是:

+---------+-------------+------------------------+
|  name   | SUM(sa.val) |       sale_date        |
+---------+-------------+------------------------+
| Store 1 |         100 | July, 29 2015 00:00:00 |
| Store 2 |         300 | July, 29 2015 00:00:00 |
+---------+-------------+------------------------+

小提琴: http://sqlfiddle.com/#!9/0faa35/40

1 个答案:

答案 0 :(得分:1)

您的加入条件不完整。请参阅以下语句中更改的“ON”子句:

SELECT st.name, SUM(sa.val), sa.sale_date FROM sales sa
  INNER JOIN employee e ON sa.employee_id=e.id
  INNER JOIN store st ON e.store_id=st.id
GROUP BY st.name, sa.sale_date
ORDER BY sa.sale_date