SQL Get “ISO Year” for ISO Week

后端 未结 4 2092
悲&欢浪女
悲&欢浪女 2021-01-05 04:34

I need to calculate the year a week is assigned to. For example the 29th december of 2003 was assigned to week one of year 2004 (this is only for europe, I think). You can t

4条回答
  •  灰色年华
    2021-01-05 04:59

    This is the most compact solution I could come up with:

    CASE
        WHEN DATEPART(ISO_WEEK, @Date) > 50 AND MONTH(@Date) = 1 THEN YEAR(@Date) - 1
        WHEN DATEPART(ISO_WEEK, @Date) = 1 AND MONTH(@Date) = 12 THEN YEAR(@Date) + 1
        ELSE YEAR(@Date) END
    

    Can be used directly inside a SELECT statement. Or you could consider creating a user-defined function that takes the @Date parameter as input and outputs the result of the case statement.

提交回复
热议问题