2012-12-03 158 views
1

考慮到包含的信息在一定時間間隔像這樣的表:計算時間間隔的總秒數

ID StartTime    EndTime 
================================================== 
1 2012-11-22 06:14:10 2012-11-22 06:18:00 
2 2012-11-22 06:16:10 2012-11-22 06:19:40 
3 2012-11-22 06:20:50 2012-11-22 06:21:20 
4 2012-11-22 06:22:30 2012-11-22 06:23:00 
5 2012-11-22 06:22:10 2012-11-22 06:24:40 
.................................................. 
.................................................. 

的問題是找到更好的T-SQL的方式爲這些間隔的考慮交叉時刻只能有一個計算總秒數時間。

例如,前三記錄總秒數是360

回答

1

下面是一個例子,該腳本是找到其中秒並沒有包括在任何行,並從秒的總和減去它的時間間隔在第一個「開始」和最後一個「結束」之間。該腳本假設開始時間始終小於或等於結束時間

select max(totalsec) - coalesce(sum(datediff(second, t.endtime, a.starttime)),0) from <table> t 
cross apply 
(select min(starttime) starttime from <table> where t.endtime < starttime) a 
cross apply(select datediff(second, min(starttime), max(endtime)) totalsec from <table>) b 
where 
not exists (select 1 from <table> where id <> t.id and t.endtime >= starttime and t.endtime < endtime) 
+0

腳本中的@t是什麼? – ADIMO

+0

@ A.DIMO現在應該已經更正了

。在我的測試中,我設置了一個表變量,並忘記替換那個變量。
代表你的表,因爲我沒有表名 –

+0

我已經試過你的腳本與這組數據的結果是NU11 1 \t 2012-11-22 06:14:10.000 \t 2012-11-22 06:18 :00.000 2012-11-22 06:16:10.000 \t 2012-11-22 06:19:40.000 2012-11-22 06:17:50.000 \t 2012-11-22 06:21:20.000 2012年11月22日06:19:30.000 \t 2012年11月22日06:23:00.000 2012年11月22日06:21:10.000 \t 2012年11月22日06:24:40.000 2012-11-22 06:22:50.000 \t 2012-11-22 06:26:20.000 2012-11-22 06:24:30.000 \t 2012-11-22 06:28:00.000 – ADIMO