I’d like to have the week number and year, for a given date, from MySQL with the following rules:
- If the date is at the end of the year, but in the first week of the next year, I need to return 1 as the week number.
- If the date is at the beginning of the year, but in the last week of the previous year, I need to return 52 (or 53) as the week number.
I’ve read the week function in MySQL but I can’t get the result I want.
Date and Time Functions: WEEK(date[,mode])
I am on the french calendar, so I have to begin the week on Monday and week 1 is the first week with more than 3 days this year.
Therefore I can only use options 1 and 3.
When I write the following queries:
-
select week (‘2012-12-31’, 3), the result is 1
-
select week (‘2012-12-31’, 1), the result is 53
When I test on the 1st Jan 2016:
-
select week (‘2016-1-1’, 3), the result is 53
-
select week (‘2016-1-1’, 1), the result is 0
Option 1 can’t be used, because I can’t detect that 2012-12-31 is in the next year.
Option 3 can be used, but I have the add two pieces of logic: if weeknumber = 1 and month = 12, year + 1 and if weekumber = 53 and month = 1 then year – 1
Does someone have a better solution?
Regards
Ok, I think I get what you’re trying to do now.
As the documentation says:
If you want the week number for the year that the week is in, they suggest using the
YEARWEEK()function, which takes the same mode arguments asWEEK():So some examples of what you’d use: