3 回答
TA贡献1804条经验 获得超8个赞
SELECT DATE_FORMAT(ec_salesorder.duedate,’%Y-%m’) as m, sum(ec_salesorder.total) as total, count(*) as so_count FROM ec_salesorder GROUP BY m ORDER BY m,也就是把duedate日期以月的形式显示,然后groupby,那么按周如何统计呢?
搜了一下mysql的manual,在这里找到一个解决方法,通过mysql的week函数来做,sql语句如下:SELECT WEEK(ec_salesorder.duedate) as m, sum(ec_salesorder.total) as total, count(*) as so_count FROM ec_salesorder GROUP BY m ORDER BY m,这个方法有个缺陷,不能显示年份,仅仅靠一个周数不方便查看统计信息。
TA贡献1802条经验 获得超10个赞
以周一作为一周的开始, 使用mysql week行数模式5:
作为周划分的标准, 比如20170101是周天, week(20170101, 5) = 0,
分WEEK_IN_MONTH, 和WEEK_IN_YEAR两种情况进行分组:
WEEK_IN_YEAR:
1 2 3 4 5 6 7 8 9 10 11 12 13 | # by sleest 2017/03/29 按每个日期所在一年中的第几周分组汇总 SELECT WEEK(MY_DATE, 5)+1 AS WEEK_OF_YEAR, COUNT(1) AS COUNT, GROUP_CONCAT(MY_DATE) AS INCLUDE_DATE FROM (SELECT '2017-01-01' AS MY_DATE UNION ALL SELECT '2017-02-08' UNION ALL SELECT '2017-02-03' UNION ALL SELECT '2017-02-01' UNION ALL SELECT '2017-01-21') TMP GROUP BY WEEK(MY_DATE, 5) + 1; |
结果:
WEEK_IN_MONTH:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # by sleest 2017/03/29 按每个日期所在每个月的第几周分组汇总 SELECT WEEK(MY_DATE, 5) - WEEK(DATE_SUB(MY_DATE, INTERVAL DAYOFMONTH(MY_DATE) - 1 DAY), 5) + 1 AS WEEK_OF_MONTH, COUNT(1) AS COUNT, GROUP_CONCAT(MY_DATE) AS INCLUDE_DATE FROM (SELECT '2017-01-01' AS MY_DATE UNION ALL SELECT '2017-02-08' UNION ALL SELECT '2017-02-03' UNION ALL SELECT '2017-02-01' UNION ALL SELECT '2017-01-21') TMP GROUP BY WEEK(MY_DATE, 5) - WEEK(DATE_SUB(MY_DATE, INTERVAL DAYOFMONTH(MY_DATE) - 1 DAY), 5) + 1 |
结果:
添加回答
举报