目的是要计算给定日期的前一周.
为了在mysql中实现这个目的
首先是这样做的:
SELECT Date_Format('20121101','%u')-1;
但这样有问题, 比如给定的日期为年度第一周, 那么这样操作不会得到上一年度的最后一周的周数, 而是-1
SELECT Date_Format('20120101','%u')-1;
因而采用下列方案, 避免年度边界问题, 基本思想就是找到日期所在周的周一, 然后再进行计算:
SELECT STR_TO_DATE(CONCAT(Date_Format(20110103,'%x%v'), ' Monday') , '%x%v %W') - interval 1 week;
之所以这样处理,参加 mysql官方手册, STR_TO_DATE(str,format) 一节的note:
You cannot use format "%X%V" to convert a year-week string to a date because the combination of a year and week
does not uniquely identify a year and month if the week crosses a month boundary. To convert a year-week to a date,
you should also specify the weekday:
mysql> SELECT STR_TO_DATE('200442 Monday', '%X%V %W');
-> '2004-10-18'
另外 SELECT STR_TO_DATE(CONCAT(Date_Format(20110103,'%x%v'), ' Monday') , '%x%v%W') - interval 1 week; 中两处标红部分一定要统一, 因为他们对一周的开始日判断不同, 不统一则会出错.
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v