mysql分组按天

mysql grouping by days

我有这个计划:

1
2
3
4
5
6
7
8
9
10
11
+-------+
|posts: |
+----+--+--------+--------------------+
| ID |   title   |      timestamp     |
+----+-----------+--------------------+
|  1 |    t1     |2011-04-05 17:54:55 |
+----+-----------+--------------------+
|  2 |    t2     |2011-04-06 09:10:11 |
+----+-----------+--------------------+
|  3 |    t3     |2011-04-07 02:07:22 |
+----+-----------+--------------------+

如何获得过去7天的帖子总数,分组如下:

1
2
3
monday: 3
Tuesday: 9
Wednesday: 2

MySQL特定解决方案:

1
SELECT WEEKDAY(timestamp_field) AS wd, count(*) FROM your_table GROUP BY wd;

1
SELECT count(*) FROM your_table GROUP BY WEEKDAY(timestamp_field);


好,

您必须选择日期、进行计数(*)并按日期分组。

1
2
3
4
5
SELECT date_format(TIMESTAMP, '%d %m')
       , COUNT(*)
FROM posts
WHERE TIMESTAMP BETWEEN FROMDATE AND TODATE
GROUP BY date_format(TIMESTAMP, '%d %m')

进一步的帮助和解释:MySQL日期格式手册

编辑:

工作日也可以使用此函数通过使用%w来实现。


查看MySQL中的日期和时间函数。