从SQL Server的日期范围中获取周

时间:2017-08-10 04:34:07

标签: sql sql-server sql-server-2008

你好,有人可以告诉我如何根据给定的日期范围(不是按年或月的周数)获得一周的数字,但是日期范围。

(defvar *acceptor* (make-instance 'easy-acceptor :port 4242))
(start *acceptor*)
(define-easy-handler (test :uri "/test") () "Pass")

结果

Eg : From Date : '6/26/2017' and To Date: '7/23/2017'

1 个答案:

答案 0 :(得分:0)

如果您对TVF(表格值函数)开放

我经常使用udf来创建动态日期/时间范围。它比递归CTE更快并且是参数驱动的。您提供日期/时间范围,DatePart和增量。

示例

Select WeekNbr = 'Week '+cast(RetSeq as varchar(10))
      ,WeekBeg = cast(RetVal as date)
      ,WeekEnd = cast(RetVal+6 as date)
 From [dbo].[udf-Range-Date]('2017-06-26','2017-07-23','WK',1)

<强>返回

WeekNbr  WeekBeg      WeekEnd
Week 1   2017-06-26   2017-07-02
Week 2   2017-07-03   2017-07-09
Week 3   2017-07-10   2017-07-16
Week 4   2017-07-17   2017-07-23

感兴趣的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<=@R2
)
/*
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) 
*/