Christy Herron
Christy Herron

Reputation: 714

MySql LEFT JOIN with COUNT

I have two tables, customers and sales. I want to count sales for each customer and create a table of sales per month for each store.

I would like to produce something like;

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

but I am having trouble getting the sales count to be correct when using the following;

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

Customers table;

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

sales table;

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

Can anyone help here?

thanks

Upvotes: 1

Views: 787

Answers (2)

user3348544
user3348544

Reputation: 1

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>

Upvotes: 0

user359040
user359040

Reputation:

(Updated) The existing query will only count sales made in the same month that the customer was added. Try this, instead:

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

Upvotes: 1

Related Questions