2016-10-25 87 views
-1

我怎樣才能使用從同一個表中兩個不對稱行之間的時間差?DATEDIFF

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

+1

你的問題還不是很清楚,圖像沒有幫助。將問題中的樣本數據*和*想要的結果與期望的結果一起放入。 –

+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] 
+0

一樣。沒有解釋代碼的作用? –

+0

@ AT-2016,請隨時進行編輯,並將其添加到答案 –

+0

@ F.Kahalaj,附:如果你喜歡你可能想要讚揚的答案 –

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 
+0

沒有解釋代碼的作用? –

+0

'value'附近的語法錯誤 –

+0

我編輯了我的答案,可以檢查一次@ F.Kahalaj – Chanukya