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

后端 未结 22 1942
没有蜡笔的小新
没有蜡笔的小新 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:45

    Here is the query that brings the week number on whatever the startday and endday of the week it may be.

    SET DATEFIRST 2    
    
    DECLARE @FROMDATE DATE='12-JAN-2015'
    -- Get the first day of month
    DECLARE @ALLDATE DATE=DATEADD(month, DATEDIFF(month, 0, @FROMDATE), 0)
    DECLARE @FIRSTDATE DATE
    
    
    ;WITH  CTE as
    (
         -- Get all dates in that month
         SELECT 1 RNO,CAST(@ALLDATE AS DATE) as DATES 
         UNION ALL
         SELECT RNO+1, DATEADD(DAY,1,DATES )
         FROM    CTE
         WHERE   DATES < DATEADD(MONTH,1,@ALLDATE)
    )
    -- Retrieves the first day of week, ie, if first day of week is Tuesday, it selects first Tuesday 
    SELECT TOP 1 @FIRSTDATE =   DATES 
    FROM    CTE 
    WHERE DATEPART(W,DATES)=1
    
    SELECT (DATEDIFF(DAY,@FIRSTDATE,@FROMDATE)/7)+1 WEEKNO
    

    For more information I have answered for the below question. Can check that.

    • How do I find week number of a date according to DATEFIRST

提交回复
热议问题