SQL Query用于对连续行之间的时间进行分组和添加

时间:2014-06-13 11:30:42

标签: mysql sql

需要SQL Query(MySQL)的帮助

假设我有一个数据表为..

enter image description here

该表具有以某些时间间隔(TIME列)为某人记录的纬度和经度位置,而DISTANCE_TRAVELLED列具有距其上一记录的距离。

如果我想知道一个人没有移动多少分钟(即DISTANCE_TRAVEKLLED< = 0.001) 我应该使用什么查询?

我们还可以按日期对数据进行分组吗?基本上我想知道这个人在特定的一天闲置多少分钟。

1 个答案:

答案 0 :(得分:2)

您需要为每条记录获取上一次。我喜欢使用相关子查询来执行此操作:

select t.*,
       (select t2.time
        from table t2
        where t2.device = t.device and t2.time < t.time
        order by time desc
        limit 1
       ) as prevtime
from table t;

现在你可以得到没有移动的分钟数,如:

select t.*, TIMESTAMPDIFF(MINUTE, prevftime, time) as minutes
from (select t.*,
             (select t2.time
              from table t2
              where t2.device = t.device and t2.time < t.time
              order by time desc
              limit 1
             ) as prevtime
      from table t
     ) t

您要求的其余部分只是添加适当的where子句或group by子句。例如:

select device, date(time), sum(TIMESTAMPDIFF(MINUTE, prevftime, time)) as minutes
from (select t.*,
             (select t2.time
              from table t2
              where t2.device = t.device and t2.time < t.time
              order by time desc
              limit 1
             ) as prevtime
      from table t
     ) t
 where distance_travelled <= 0.001
group by device, date(time)

编辑:

为了提高效果,请在table(device, time)上创建索引。