2016-12-14 70 views
0

有人可以幫助我得到基於年周整數像201648而不關心設置@@firstdate屬性的週末的第一天和最後一天。我想在datetime格式的星期一開始iso date我怎樣才能得到從YYYWW在tsql的第一天

+2

的可能的複製[獲取在T-SQL從週數日期(HTTP://計算器。 com/questions/607817/get-dates-from-a-week-number-in -t-sql) –

回答

1

經過一番考慮之後,我認爲我的動態日期/時間範圍UDF可能對此有所幫助。我使用這個UDF來生成動態日期/時間範圍。您可以提供所需的日期範圍,日期部分和增量。在這種情況下,無論日期部分(WK,..)如何,我們都會按照要求獲取第N個星期一。

Declare @YYYYWW int = 201648 

Select WkNbr = B.RetSeq 
     ,WkBeg = B.RetVal 
     ,WkEnd = DateAdd(DD,6,B.RetVal) 
From (
     Select MinDate=Min(RetVal) 
     From [dbo].[udf-Range-Date](DateFromParts(Left(@YYYYWW,4),1,1),DateFromParts(Left(@YYYYWW,4),1,10),'DD',1) 
     Where DateName(DW,RetVal)='Monday' 
     ) A 
Cross Apply (Select * From [dbo].[udf-Range-Date](A.MinDate,DateFromParts(Left(@YYYYWW,4),12,31),'DD',7)) B 
Where B.RetSeq = Right(@YYYYWW,2) 

返回

WkNbr WkBeg   WkEnd 
48  2016-11-28 2016-12-04 

的UDF如果有興趣

CREATE FUNCTION [dbo].[udf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int) 
Returns Table 
Return (
    with cte0(M) As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End), 
     cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)), 
     cte2(N) As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h), 
     cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2) 

    Select RetSeq = N+1 
      ,RetVal = D 
    From cte3,cte0 
    Where D<[email protected] 
) 
/* 
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS 
Syntax: 
Select * from [dbo].[udf-Range-Date]('2016-10-01','2020-10-01','YY',1) 
Select * from [dbo].[udf-Range-Date]('2016-01-01','2017-01-01','MM',1) 
*/ 
1
declare @yrwk int = 201648 
declare @yr int = left(@yrwk,4) 
declare @wk int = right(@yrwk,2) 

select dateadd (week, @wk, dateadd (year, @yr-1900, 0)) - 4 - datepart(dw, dateadd (week, @wk, dateadd (year, @yr-1900, 0)) - 4) + 1 

--returns 11/27/2016 which is Sunday of that week (start of week) 
--change +1 to +2 at the end for "Monday" 
+1

我會被蘸!從未考慮INT的左/右。只爲那個偷IT + –

+0

對於那個小竅門,我無法感謝你。我把自己扭曲成了一個int的位置。 –

+0

HAHA不用擔心@JohnCappelletti。也許這是我心靈的簡單。 – scsimon