我有这个东西
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
答案 0 :(得分:1)
如果日期是日期时间或时间戳,则您当前的查询应该有效:
SELECT DATE_FORMAT(`date`,'%m/%Y') as period,
COUNT(distinct customer) as total
FROM Orders
WHERE YEAR(`date`) = 2012
GROUP BY period
请参阅Demo