2012-12-03 235 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