2016-12-14 43 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