MySQL按周期计算不同的客户和订单



我有这些东西

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

我需要在一年内逐月计算所有活跃客户,例如:

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

但是groupby和DISTINCT不能很好地工作,这个SQL在同一时间段返回很多结果

@edit将导致此

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

和我期待这个

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

如果日期是日期时间或时间戳,则当前查询应该工作:

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

看到演示

相关内容

最新更新