2018-12-12 补充
php date函数 'W' 获取到的星期数,经测试发现相当于mysql yearweek函数的第二个参数为3的获取的值
-----------------------------------------------------------------------分割线-------------------------------------------------------------------------------------
mysql的这个两个函数都可以用来计算一个日期所属周是该年的第几周,用于对自然周进行统计查询
1.MySQL 的 YEARWEEK 是获取年份和周数的一个函数,函数形式为 YEARWEEK(
date
[,mode
])
例如 2010-3-14 ,礼拜天
SELECT YEARWEEK('2010-3-14') 返回 11
SELECT YEARWEEK('2010-3-14',1) 返回 10
其中第二个参数是 mode ,具体指的意思如下:
Mode | First day of week | Range | Week 1 is the first week … |
0 | Sunday | 0-53 | with a Sunday in this year |
1 | Monday | 0-53 | with more than 3 days this year |
2 | Sunday | 1-53 | with a Sunday in this year |
3 | Monday | 1-53 | with more than 3 days this year |
4 | Sunday | 0-53 | with more than 3 days this year |
5 | Monday | 0-53 | with a Monday in this year |
6 | Sunday | 1-53 | with more than 3 days this year |
7 | Monday | 1-53 | with a Monday in this year |
2、date_format函数不止可以返回周,也可以返回月日时
按周
select DATE_FORMAT(create_time,'%Y%u') weeks,count(caseid) count from tc_case group by weeks;
按月
select DATE_FORMAT(create_time,'%Y%m') months,count(caseid) count from tc_case group by months;
按天
select DATE_FORMAT(create_time,'%Y%m%d') days,count(caseid) count from tc_case group by days;
按小时
select DATE_FORMAT(create_time,'%Y%m%d%H') hours,count(caseid) count from tc_case group by hours;
20181231是周一,现在我们执行跨年查询
这里需要注意上面对yearweek函数的第二个参数的解释,值为0时,这一周的Sunday在哪一年就将该周算给这一年
SELECT
SUM(total_pay_money) AS money,
YEARWEEK(pay_date) as date
FROM
sy_day_pay
WHERE
pay_date BETWEEN '20181231'
AND '20190105'
GROUP BY date;
第二个参数值为1时,这一周在哪一年的天数大于3天,就算给哪一年
SELECT
SUM(total_pay_money) AS money,
YEARWEEK(pay_date,1) as date
FROM
sy_day_pay
WHERE
pay_date BETWEEN '20181230'
AND '20190105'
GROUP BY date;
查询结果
然后是date_format的执行效果
SELECT
SUM(total_pay_money) AS money,
DATE_FORMAT(pay_date,'%Y%u') weeks
FROM
sy_day_pay
WHERE
pay_date BETWEEN '20181231'
AND '20190105'
GROUP BY weeks
很显然,它将在同一周的日期分给了不同的年份
结论是当我们希望执行跨年的按周统计时,使用yearweek更合适,无论它将这一周给了哪一年,都是只生成一组数据,而不会变成两个