【问题标题】:Better way to summarize data about stop times?总结停止时间数据的更好方法?
【发布时间】:2010-06-24 19:00:48
【问题描述】:

这个问题接近于这个:

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 表。有没有在不使用临时表的情况下查询这个?

谢谢。

【问题讨论】:

    标签: sql algorithm tsql optimization


    【解决方案1】:

    您不能在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-20
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      相关资源
      最近更新 更多