2

ISO-8601 规定周数的格式应为YYYY-W##- 请注意周数应为两位数,如 01、02、...


SELECT cast(DATEPART(YYYY, CreationDate) as varchar) + '-W' + 
       cast(DATEPART(ISO_WEEK, GETDATE())`

问题是这将周数设为 1、2、...

提取2020-W01的正确方法是什么,...

4

2 回答 2

4

原始问题文本与 ISO_WEEK 编号的简单格式问题有关,但我觉得这里有一个更大的问题,即年份部分的连接。简单地连接 DatePart YYYY 和 ISO_WEEK 将在第 1 周和/或第 53 周产生不正确(或至少是意外)的结果。值得注意的是,像 2014-12-31 这样的日期是第 1 周的一部分,但不是 2014-W01。它是 2015-W01 的一部分。同样,2016-01-01 将是 2015-W53 的一部分,而不是 2016-W53。为了确定 Iso Year-Week,必须更正年份以考虑到这一点:

With
    Dates (Date) As (
            Select Convert( date, N'2014-12-31' )
Union All   Select Convert( date, N'2015-01-01' )
Union All   Select Convert( date, N'2015-12-31' )
Union All   Select Convert( date, N'2016-01-01' )
    )
Select
    src.Date
,   Concat( Case
        When DatePart( Month, src.Date ) = 12 And DatePart( ISO_WEEK, src.Date ) = 1 Then DatePart( Year, src.Date ) + 1
        When DatePart( Month, src.Date ) = 1 And DatePart( ISO_WEEK, src.Date ) > 50 Then DatePart( Year, src.Date ) - 1
        Else DatePart( Year, src.Date )
    End, N'-W', Right( Concat( N'00', DatePart( ISO_WEEK, src.Date ) ), 2 ) ) As IsoYearWeek
From
    Dates src
;
于 2015-11-16T13:20:41.343 回答
3
SELECT cast(DATEPART(YYYY, CreationDate) as varchar) + '-W' + Right('0'+cast(DATEPART(ISO_WEEK,CreationDate) as Varchar),2)
于 2012-11-10T13:54:07.443 回答