这个问题接近于此:
Find the period of over speed?
这是我的表:
Longtitude Latitude Velocity Time
102 401 40 2010-06-01 10:22:34.000
103 403 50 2010-06-01 10:40:00.000
104 405 0 2010-06-01 11:00:03.000
104 405 0 2010-06-01 11:10:05.000
105 406 35 2010-06-01 11:15:30.000
106 403 60 2010-06-01 11:20:00.000
108 404 70 2010-06-01 11:30:05.000
109 405 0 2010-06-01 11:35:00.000
109 405 0 2010-06-01 11:40:00.000
105 407 40 2010-06-01 11:50:00.000
104 406 30 2010-06-01 12:00:00.000
101 409 50 2010-06-01 12:05:30.000
104 405 0 2010-06-01 11:05:30.000
我想总结一下车辆停止的时间(速度= 0),包括:它从“何时”到“何时”停止了多少分钟,停止了多少次以及停止了多长时间。
我写了这个查询来做到这一点:
select longtitude, latitude, MIN(time), MAX(time), DATEDIFF(minute, MIN(Time), MAX(time))
as Timespan from table_1 where velocity = 0 group by longtitude,latitude
select DATEDIFF(minute, MIN(Time), MAX(time)) as minute into #temp3
from table_1 where velocity = 0 group by longtitude,latitude
select COUNT(*) as [number]from #temp
select SUM(minute) as [totaltime] from #temp3
drop table #temp
此查询返回:
longtitude latitude (No column name) (No column name) Timespan
104 405 2010-06-01 11:00:03.000 2010-06-01 11:10:05.000 10
109 405 2010-06-01 11:35:00.000 2010-06-01 11:40:00.000 5
number
2
totaltime
15
你可以看到,它工作正常,但我真的不喜欢#temp表。反正有没有使用临时表来查询这个?
谢谢。
答案 0 :(得分:2)
您无法在SQL Server中嵌套聚合(例如SUM(DATEDIFF(minute, MIN(Time), MAX(time)))
,但可以使用派生表而不是临时表。
SELECT SUM(minute) FROM
(
select DATEDIFF(minute, MIN(Time), MAX(time)) as minute
from table_1 where velocity = 0 group by longtitude,latitude
) derived