获得每组中元素之间的最小差异

时间:2014-01-28 18:55:51

标签: mysql sql

我有一个以下形式的mysql表:

  • timestamp(unix timestamp)
  • 一些值列[...]
  • GROUPID

现在我想构建一个按groupid分组的查询,并打印组中每个时间戳之间的最小时间差。

类似SELECT groupid,MIN(??? - ???)as minimum_time_diff FROM mytable GROUP BY groupid;

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

一种方法是使用自我加入和group by

select t1.groupid, min(timestampdiff(second, t1.timestamp, t2.timestamp)) as minsecs
from table t1 join
     table t2
     on t1.groupid = t2.groupid and t1.timestamp < t2.timestamp
group by t1.groupid;

您也可以使用变量执行此操作:

select groupid, min(timestampdiff(second, prevtimestamp, timestamp))
from (select t.*,
             if(@groupid = groupid, @prevtimestamp, NULL) as prevtimestamp,
             @prevtimestamp := timestamp,
             @groupid = groupid
      from table t cross join
           (select @prevtimestamp := 0, @groupid = '')
      order by groupid, timestamp
     ) t
group by groupid;

这使用的观察结果是,当订购时间戳时,两个相邻行之间将发生最小差异。