如何使用sql在一个日期范围内设置?

时间:2011-03-18 22:14:34

标签: sql

我的约会

Dates
2011-03-01 00:00:00.000
2011-03-03 00:00:00.000
2011-03-07 00:00:00.000
2011-03-08 00:00:00.000
2011-03-13 00:00:00.000
2011-03-14 00:00:00.000
2011-03-15 00:00:00.000

如何将此日期转换为如下所示的一个日期范围

我需要这样的输出'

Date_from                 Date_to
2011-03-01 00:00:00.000   2011-03-01 00:00:00.000
2011-03-03 00:00:00.000   2011-03-03 00:00:00.000
2011-03-07 00:00:00.000   2011-03-08 00:00:00.000 
2011-03-13 00:00:00.000   2011-03-15 00:00:00.000

1 个答案:

答案 0 :(得分:2)

SQL Server 2005 +

;WITH cte
     AS (SELECT *,
                DATEDIFF(DAY, 0, Dt) - 
                        DENSE_RANK() OVER (ORDER BY DATEDIFF(DAY,0,Dt)  ) AS Grp
         FROM   Dates)
SELECT MIN(Dt) AS Date_from,
       MAX(Dt) AS Date_to
FROM   cte
GROUP  BY Grp