在SQL Server中将日期列表转换为日期范围

时间:2016-06-01 20:52:15

标签: sql sql-server date

我的查询如下:

public class ASCII {

public static void main(String[] args) {

    for (int ascii = 43; ascii <= 120; ascii++) {
        System.out.print((char)ascii + "  ");
    }

}

结果是:

SELECT  [Date] FROM [TableX] ORDER  BY [Date]

我如何获得以下配对?

2016-06-01
2016-06-03
2016-06-10
2016-06-11

5 个答案:

答案 0 :(得分:3)

如果您使用的是SQL Server 2012或更高版本,则可以使用LEAD方法。

  

在不使用SQL Server 2016中的自联接的情况下访问同一结果集中后续行的数据.LEAD提供对当前行之后的给定物理偏移量的行的访问。

我认为这对你来说会是这样的:

SELECT [Date] AS [From], LEAD([Date], 1) OVER (ORDER BY [Date]) AS [To]
FROM TableX
ORDER BY [Date]

请注意,在最后一行,[收件人]字段为NULL。如果要删除该行,可以将其放在内部查询中:

SELECT *
FROM 
(
    SELECT [Date] AS [From], LEAD([Date], 1) OVER (ORDER BY [Date]) AS [To]
    FROM TableX
) x
WHERE [To] IS NOT NULL

答案 1 :(得分:3)

您需要做的就是为每个date添加一个行号。

然后将所有这些行统一到下一行(最后一行除外)

WITH cteDates AS
(
    SELECT  [Date],
            ROW_NUMBER() OVER (ORDER BY (SELECT [Date])) As RowNum
    FROM    TableX
)

SELECT  TOP(SELECT COUNT(*) - 1 FROM cteDates)
            [Date] [From],
            (SELECT [Date] FROM cteDates WHERE RowNum = d.RowNum + 1) [To]
FROM    cteDates d

答案 2 :(得分:2)

以下查询适用于 SQL2005 +

WITH CteSourceDt
AS (
    SELECT  
        a.ColDt, ROW_NUMBER() OVER(ORDER BY a.ColDt) AS RowNum
    FROM (VALUES 
        ({d '2016-06-01'}),
        ({d '2016-06-03'}),
        ({d '2016-06-10'}),
        ({d '2016-06-11'}),
        ({d '2016-06-15'})
    ) a(ColDt)
)

SELECT  crt.ColDt AS FromDt, nxt.ColDt AS ToDt
FROM    CteSourceDt crt 
LEFT JOIN CteSourceDt nxt ON crt.RowNum = nxt.RowNum - 1

答案 3 :(得分:2)

SQL 2008的一个棘手的解决方案。

declare @tbl table(dt datetime)
insert @tbl values
('2016-06-01'),
('2016-06-03'),
('2016-06-10'),
('2016-06-11')

;with cte as (
select dt, ROW_NUMBER() over(order by dt) rn --add number
from @tbl
),
newTbl as (
select t1.dt start, t2.dt [end]
from cte t1 inner join cte t2 on t1.rn+1=t2.rn
)
select *
from newTbl

结果就是你想要的。

答案 4 :(得分:0)

由于您所说的没有任何差距,您可以使用DATEADD()

 SELECT DISTINCT 
       [Date] as [FROM],
       DATEADD(DAY,1,[Date]) as [TO]
    FROM TableX
    ORDER BY [Date] DESC