按年和月计算总数

时间:2011-03-02 10:45:51

标签: mysql date group-by aggregate

我有一个看起来像这样的表:

id,created,action
1,'2011-01-01 04:28:21','signup'
2,'2011-01-05 04:28:21','signup'
3,'2011-02-02 04:28:21','signup'

如何选择和分组这些输出为:

year,month,total
2011,1,2
2011,2,1

2 个答案:

答案 0 :(得分:48)

试试这个:

SELECT DATE_FORMAT(created, '%Y') as 'year',
DATE_FORMAT(created, '%m') as 'month',
COUNT(id) as 'total'
FROM table_name
GROUP BY DATE_FORMAT(created, '%Y%m')

答案 1 :(得分:6)

SELECT YEAR(created) as year_val, MONTH(created) as month_val ,COUNT(*) as total
FROM testing
GROUP BY YEAR(created), MONTH(created)