MySQL Getting Records over the Last Working Week

戏子无情 提交于 2019-12-08 06:40:45

问题


I'm using

 WHERE WEEK(curdate,3)-WEEK(date)=1 

to get all lines of a table that are recorded on the last working week (Monday to Sunday). Works well the whole year, but in January that will return 0 for some time, so I have to take

 WHERE WEEK(curdate,3)+53-WEEK(date)

in that case. I can't use OR because it would take both current year info and last year info when both exist. I already tried COALESCE and IFNULL methods:

 WHERE COALESCE(
     (WEEK(curdate(),3)-WEEK(date,3) = 1),
     (WEEK(curdate(),3)+53-WEEK(date,3) = 1
 )

It works well for the whole year but doesn't manage the case when IFNULL is true. Please give me advice on effective handling of this case.


回答1:


You can get the date of the Monday of the current week using:

select SUBDATE(curdate(), WEEKDAY(curdate()));

and then use the date of the Monday of this week and the Monday of the previous week in your predicate:

WHERE date >= SUBDATE(curdate(), WEEKDAY(curdate())) - interval 1 week
AND date < SUBDATE(curdate(), WEEKDAY(curdate()))


来源:https://stackoverflow.com/questions/15154655/mysql-getting-records-over-the-last-working-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!