如何在MySQL中使用GROUP BY(日期)在一周的给定日期开始

时间:2011-09-26 13:08:24

标签: mysql group-by

如果我有一个MySQL查询按周汇总总数,例如:

select sum(keyword1), sum(keyword2), sum(keyword3), dateTime
from myTable
group by week(dateTime)
order by dateTime asc

我发现这几周似乎是在星期天开始的。

这可以改为星期一吗?

列dateTime采用MySQL时间戳格式2011-09-26 12:34:32。

2 个答案:

答案 0 :(得分:6)

你希望星期日属于前一周,所以从中删除一天

select sum(keyword1), sum(keyword2), sum(keyword3),  week(DATE_SUB(dateTime, INTERVAL 1 DAY)) my_week
from myTable
group by week(DATE_SUB(dateTime, INTERVAL 1 DAY))
order by my_week asc

答案 1 :(得分:4)

mysql> select week('2011-09-25', 1);
+-----------------------+
| week('2011-09-25', 1) |
+-----------------------+
|                    38 |
+-----------------------+

mysql> select week('2011-09-25', 0);
+-----------------------+
| week('2011-09-25', 0) |
+-----------------------+
|                    39 |
+-----------------------+

所以,http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_default_week_format