通过开始日期计算时间范围

时间:2016-12-14 10:47:14

标签: sql-server tsql

说,我有一张表"开始"日期

ID     Start
1      null      
2      2001-1-1
3      2002-1-1

现在,我需要以有效的方式计算每条记录的有效时间范围:

ID     Start     Finish
1      null      2000-12-31
2      2001-1-1  2001-12-31
3      2002-1-1  null

2 个答案:

答案 0 :(得分:2)

使用LEAD:

create table #dates
(
    ID int,
    Start date
)

insert into #dates values(1,null),(2,'01-jan-2001'),(3,'01-jan-2002')

select ID,
    Start,
    DATEADD(DD, -1, LEAD(Start,1) over (order by Start)) AS Finish
from #dates

答案 1 :(得分:0)

使用JOIN

<强>查询

select t1.[ID], t1.[Start], 
dateadd(day, -1, t2.[Start]) as [Finish]
from [your_table_name] t1
left join [your_table_name] t2
on t1.ID = t2.ID - 1;

<强> Demo 1

正如HABO所提到的,如果Id的顺序不正确。然后按ID列提供行号。

<强>查询

;with cte as(
  select [row_num] = row_number() over(
    order by [ID]
  ),*
  from [your_table_name]
)
select t1.[ID], t1.[Start], 
dateadd(day, -1, t2.[Start]) as [Finish]
from cte t1
left join cte t2
on t1.[row_num] = t2.[row_num] - 1;

<强> Demo 2