在同一个表中的2个不对称列之间的约会

时间:2016-10-25 11:56:06

标签: sql sql-server datediff

如何使用来自同一table的两个不对称行之间的日期差异?

select 
[endtime]
,[realtime]
from [prin]
where ([realtime] is not null) and ([endtime] is not null and) 
order by [realtime] 

between end date time and next start date time

2 个答案:

答案 0 :(得分:1)

使用DateDiff功能获取两个日期之间的差异。 添加day参数以获得天数差异。

SELECT 
[endtime]
,[realtime]
,datediff (day,[endtime],lead ([realtime]) over (order by [realtime])) as days_endtime_2_next_realtime
FROM [prin]
WHERE ([realtime] is not null) 
AND ([endtime] is not null) 
ORDER BY [realtime] 

答案 1 :(得分:0)

create table #a
(
date_1 date,
date_2 date
)

insert into #a values
 ('1-10-16','2-10-16'),
 ('2-10-16','3-10-16'),
 ('3-10-16','4-10-16')

 ;with cte as
(
select 
date_1,date_2
,lead(date_2,1) over (order by date_2 ) as lead_value
from #a
where (date_1 is not null) and (date_2 is not null )  
)
select date_1,date_2,
datediff(Day,date_1,lead_value) as diffrence from cte