1

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

我想制作类似的东西;

------------------------------
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       |

有人可以在这里帮忙吗?

谢谢

4

2 回答 2

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);
于 2013-06-04T12:24:37.383 回答
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>
于 2014-02-24T21:24:01.023 回答