Get Month from Calendar Week (SQL Server)

后端 未结 2 1090
-上瘾入骨i
-上瘾入骨i 2021-01-20 03:16

I have the following problem:

In Microsoft\'s SQL Server, I have a table where a year and a calendar week (starting with Monday) is stored. Now, I want to write a fu

2条回答
  •  不知归路
    2021-01-20 03:54

    Edited: I had to reread answer and pull from M.Ali to get the full answer. You also have to know the correct year if the first week starts in the previous year. You may need to do some editing if your first week of the year doesn't necessarily include 1 Jan.

    DECLARE @Week int, @Year int, @Date datetime;
    
    SET @Week = 1
    SET @Year = 2014
    SET @Date = CAST(@Year as varchar(4)) + '-01-01'
    SELECT @Date = DATEADD(ww, @week-1, @Date)
    
    SELECT MONTH(DATEADD(d, (DATEPART(dw,@date)-2)*-1, @date)), 
      CASE WHEN @Week = 1 AND MONTH(DATEADD(d, (DATEPART(dw,@date)-2)*-1, @date)) = 12 
        THEN @YEAR - 1 ELSE @YEAR END as CorrectYear
    

提交回复
热议问题