Ragen Dazs
Ragen Dazs

Reputation: 2170

MySQL count distinct Customers from Orders by period

I have this stuff

mysql> explain Order;
+------------------------+-------------------+------+-----+-----------+----------------+
| Field                  | Type              | Null | Key | Default   | Extra          |
+------------------------+-------------------+------+-----+-----------+----------------+
| id                     | int(11) unsigned  | NO   | PRI | NULL      | auto_increment |
| date                   | timestamp         | NO   |     | NULL      |                |
| customer               | int(11) unsigned  | NO   |     | NULL      |                |
| address                | int(11) unsigned  | NO   |     | NULL      |                |
+------------------------+-------------------+------+-----+-----------+----------------+

And I need to count all active customers month by month in one year, for example:

SELECT 
  DATE_FORMAT(`date`,'%m/%Y') as period,
  COUNT(DISTINCT(customer)) as total

FROM
  Order

WHERE
  YEAR(`date`) = '2012'

GROUP BY
  period

But GROUP BY with DISTINCT are not working well and this SQL are returning a lot of results for the same period

@edit Will result this

07/2012 1
07/2012 1
06/2012 1
09/2012 1
12/2012 769
06/2012 1
07/2012 1
07/2012 1
06/2012 1
06/2012 1
10/2012 1
... a lot of results with 1 as total

And I'm expecting this

01/2012 329
02/2012 279
03/2012 229
04/2012 379
05/2012 411
06/2012 152
07/2012 277
08/2012 411
09/2012 468
10/2012 501
11/2012 488
12/2012 593

Upvotes: 0

Views: 573

Answers (1)

Taryn
Taryn

Reputation: 247670

Your current query should work if the date is a datetime or a timestamp:

SELECT DATE_FORMAT(`date`,'%m/%Y') as period,
  COUNT(distinct customer) as total
FROM Orders
WHERE YEAR(`date`) = 2012
GROUP BY period

See Demo

Upvotes: 1

Related Questions