参数日期之间的周数 - 按周分组 - SQL

时间:2013-07-09 11:13:10

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

我的存储过程中有2个参数@FromDate和@ToDate,我想计算@FromDate和@ToDate之间的周数,@ IceDate总是星期一,而@ToDate总是星期天,但日期可以涵盖周,月等。

目前我有DATEDIFF(WW,@ FrDate,@ ToDate)

哪个返回说4但我希望它返回4行中的1,2,3和4而不是仅仅1行。

实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

如果我做得对:

With T( Number ) as
(
    Select 0 as Number
        union all
    Select Number + 1
        from T
        where Number < DATEDIFF(WW, @FromDate, @ToDate)

)

SELECT NUMBER FROM T WHERE Number>0;

SQLFiddle demo

答案 1 :(得分:0)

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME

SET @StartDate = GETUTCDATE() - 90
SET @EndDate = GETUTCDATE() 

DECLARE @WeekNumber INT

SET @WeekNumber = DATEDIFF(WW, @StartDate, @EndDate) ;

WITH    CTE_WeekNumber ( WeekNumber )

      AS ( SELECT   1
           WHERE    @WeekNumber >= 1
           UNION ALL
           SELECT   WeekNumber + 1
           FROM     CTE_WeekNumber
           WHERE    @WeekNumber >= WeekNumber + 1
         )

SELECT  *
FROM    CTE_WeekNumber