In MySQL, how to return the week of the month?

前端 未结 6 1873
独厮守ぢ
独厮守ぢ 2020-12-10 15:17

The year is divided into 12 months. We can break down a month in four weeks.

In MySQL, how to return the week of the month? (Example: first week: 2 entries, second w

相关标签:
6条回答
  • 2020-12-10 15:22

    Week of month (where the starting incomplete week is counted as a whole)

    select ceiling((day(now()) - 
    (6 - weekday(date_format(now(),'%Y-%m-01'))))/7) 
    + case when 6 - weekday(date_format(now(),'%Y-%m-01'))> 0 
    then 1 else 0 end week_of_month;
    
    0 讨论(0)
  • 2020-12-10 15:24

    SELECT (WEEK('2020-09-27') - WEEK(DATE_FORMAT('2020-09-27','%Y-%m-01')))+1

    0 讨论(0)
  • 2020-12-10 15:33
    SELECT WEEK(my_date_field,5) - WEEK(DATE_SUB(my_date_field, 
    INTERVAL DAYOFMONTH(my_date_field) - 1 DAY),5) + 1
    

    Or you can see here.

    0 讨论(0)
  • 2020-12-10 15:37
    FLOOR((DayOfMonth(dateCol)-1)/7)+1
    

    I'd like to make it clear that this is probably not a good way to divide your data - (see the comments), but that this will get you as close as you can get.

    0 讨论(0)
  • 2020-12-10 15:42

    Use the MySQL built-in function week to find the week number for the year, then subtract the week number for the first day of the month.

    SELECT WEEK('2012-02-20') - WEEK('2012-02-01')
    

    there are plenty of options in the documentation to customize the call to fit exactly what you are looking for, but I hope my example gives you an idea of what is available to you.

    http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week

    0 讨论(0)
  • 2020-12-10 15:47
    TO_CHAR(my_date, 'W') 
    

    Returns exact number of week in particular month.

    0 讨论(0)
提交回复
热议问题