Question

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.

Was it helpful?

Solution

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()))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top