从单个日期列中选择并创建多个开始和结束记录

时间:2014-10-15 13:16:02

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

我真的很想解决这个问题,但有一点需要你把它放在那里,学习并继续前进。

我有一个临时表,其中包含1列POCDates,这是一个日期列表,其中一些是连续的/连续的。例如:

POCDates
01/01/2014
02/01/2014
03/01/2014
04/01/2014
10/03/2014
11/03/2014
25/03/2014
26/03/2014
28/03/2014

我希望在我的程序中运行一个查询,该查询将从此临时表中进行选择,并使用上面的示例数据显示以下内容:

POCDatesSummary
Start        End         Count
01/01/2014   04/01/2014  4
10/03/2014   11/03/2014  2
25/03/2014   26/03/2014  2
28/03/2014   28/03/2014  1

计数不是必需的,但我怀疑这是使用DATEDIFF最简单的部分,所以我把它留在那里。

我尝试过多种方法,并针对类似问题搜索论坛;一切都没有结束。希望我能在这里找到答案。

1 个答案:

答案 0 :(得分:0)

使用递归CTE:

;WITH cte1 AS (
    SELECT  POCDates, ROW_NUMBER() OVER (ORDER BY POCDates) AS RowNumber
    FROM    MyTable
), cte2 AS (
    SELECT  POCDates,
            POCDates AS RangeStart,
            POCDates AS RangeEnd,
            RowNumber
    FROM    cte1
    WHERE   RowNumber = 1
    UNION ALL
    SELECT      c1.POCDates,
                CASE
                    WHEN c1.POCDates = DATEADD(day,1,c2.POCDates) THEN c2.RangeStart
                    ELSE c1.POCDates
                END             AS RangeStart,
                c1.POCDates     AS RangeEnd,
                c1.RowNumber
    FROM        cte2 c2
    INNER JOIN  cte1 c1 ON c1.RowNumber = c2.RowNumber + 1
) 

SELECT  RangeStart          AS [Start],
        MAX(RangeEnd)       AS [End],
        COUNT(RangeStart)   AS [Count]
FROM    cte2
GROUP BY RangeStart
OPTION  (MAXRECURSION 0)

MAXRECURSION 0允许CTE无限重复。默认值为10,如果表的行数超过10行,将导致查询失败。