我有这个东西
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
但是带有 DISTINCT 的 GROUP BY 效果不佳,并且此 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