How to get week number of the month from the date in sql server 2008

后端 未结 22 1822
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 15:52

In SQL Statement in microsoft sql server, there is a built-in function to get week number but it is the week of the year.

Select DatePart(week, \'2012/11/30\         


        
相关标签:
22条回答
  • 2020-11-27 16:50
    declare @end_date datetime = '2019-02-28';
    select datepart(week, @end_date) - datepart(week, convert(datetime, substring(convert(nvarchar, convert(datetime, @end_date), 127), 1, 8) + '01')) + 1 [Week of Month];
    
    0 讨论(0)
  • 2020-11-27 16:52
    DECLARE @DATE DATETIME
    SET @DATE = '2013-08-04'
    
    SELECT DATEPART(WEEK, @DATE)  -
        DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,@DATE), 0))+ 1 AS WEEK_OF_MONTH
    
    0 讨论(0)
  • 2020-11-27 16:55

    Just look at the date and see what range it falls in.

    Range 1-7 is the 1st week, Range 8-14 is the 2nd week, etc.

    SELECT 
    CASE WHEN DATEPART(day,yourdate) < 8 THEN '1' 
      ELSE CASE WHEN DATEPART(day,yourdate) < 15 then '2' 
        ELSE CASE WHEN  DATEPART(day,yourdate) < 22 then '3' 
          ELSE CASE WHEN  DATEPART(day,yourdate) < 29 then '4'     
            ELSE '5'
          END
        END
      END
    END
    
    0 讨论(0)
  • 2020-11-27 16:55
    WeekMonth = CASE WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 22 THEN '5' 
                     WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 15 THEN '4' 
                     WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 8 THEN '3'
                     WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 1 THEN '2' 
                     ELSE '1'
                 END 
    
    0 讨论(0)
提交回复
热议问题