MySql LEFT JOIN与COUNT

时间:2013-06-04 11:56:30

标签: mysql count left-join

我有两张桌子,顾客和销售。我想计算每个客户的销售额,并为每个商店创建一个每月销售额表。

我想生产类似的东西;

------------------------------
month  |  customers  | sales  |
------------------------------
1/2013 |      5      |   2    |
2/2013 |      21     |   9    |
3/2013 |      14     |   4    |
4/2013 |      9      |   3    |

但在使用以下内容时,我无法确保销售计数正确无误;

SELECT CONCAT(MONTH(c.added), '/', YEAR(c.added)), count(c.id), count(s.id)
FROM customers c
LEFT JOIN sales s 
ON s.customer_id = c.id AND MONTH(c.added) = MONTH(s.added) AND YEAR(c.added) = YEAR(s.added)
WHERE c.store_id = 1
GROUP BY YEAR(c.added), MONTH(c.added);

客户表;

-------------------------------
id    |   store_id  | added    |
-------------------------------
1     |      1      |2013-02-01 |
2     |      1      |2013-02-02 |
3     |      1      |2013-03-16 |

销售表;

---------------------------------
id    |   added    | customer_id |
---------------------------------
1     | 2013-02-18 |     3       |
2     | 2013-03-02 |     2       |
3     | 2013-03-16 |     3       |

有人可以帮忙吗?

感谢

2 个答案:

答案 0 :(得分:1)

(已更新)现有查询仅计算在添加客户的同一个月内进行的销售。试试这个,而不是:

SELECT CONCAT(MONTH(sq.added), '/', YEAR(sq.added)) month_year,
       sum(sq.customer_count), 
       sum(sq.sales_count)
FROM (select s.added, 0 customer_count, 1 sales_count
      from customers c
      JOIN sales s ON s.customer_id = c.id
      WHERE c.store_id = 1
      union all
      select added, 1 customer_count, 0 sales_count
      from customers
      WHERE store_id = 1) sq
GROUP BY YEAR(sq.added), MONTH(sq.added);

答案 1 :(得分:0)

SELECT c.* , s.sales_count<br>
FROM customers c<br>
LEFT JOIN (SELECT customer_id, count(id) as sales_count FROM sales GROUP BY customer_id) s on c.id=s.customer_id<br>
WHERE c.store_id = 1<br>