SELECT WEEK(my_date_field,5) - 
WEEK(DATE_SUB(my_date_field, INTERVAL DAYOFMONTH(my_date_field)-1 DAY),5)+1

Recently I needed to get the number of the week in a certain month. There is the handy WEEK() function, however it only gives you the week of the year.

Obviously before we can go through the code above, a definition of the nth week of the month is needed (as I realized after asking the question on stackoverflow…):

For me the week starts on a Monday, and the first week of the month does not have to be a full week – if a month starts on a Friday, the Friday to Sunday days count as the first week.

With this out of the way here is a quick explanation of what goes on above.

WEEK(my_date_field,<strong>5</strong>)

First we get the actual week number of the year for the specified date. The second parameter is there to define Monday as the first day of the week (more details in Mysql manual).

DAYOFMONTH(my_date_field)

Next we get the day of the month for the specified date.

DATE_SUB(my_date_field, <strong>DAYOFMONTH(my_date_field)</strong>-1 DAY)

We can use that number with DATE_SUB to get the date for the 1st day of the month. This in turn can be used to get the week number for the 1st week of the month.

SELECT WEEK(my_date_field,5) - 
WEEK(<strong>DATE_SUB(my_date_field, INTERVAL DAYOFMONTH(my_date_field)-1 DAY)</strong>,5)+1

Finally we subtract the first day’s week from the actual week number which should give us the month’s week number starting from 0. Thus the final +1 if you want the count to start from 1.