我有这个东西
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
但是 GROUP BY 和 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
参见Demo
关于MySQL 按时间段对订单中的不同客户进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747967/