简体   繁体   English

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

[英]Get minimum diff between elements in each group

I have a mysql table in the following form: 我有以下形式的mysql表:

  • timestamp (unix timestamp) 时间戳(unix时间戳)
  • some value columns [...] 一些值列[...]
  • groupid 组号

Now I want to build a query which groups by groupid and prints the minimum time difference between each of the timestamps in the group. 现在,我想构建一个按groupid分组的查询,并打印出该分组中每个时间戳之间的最小时间差。

Something like SELECT groupid, MIN(??? - ???) as minimum_time_diff FROM mytable GROUP BY groupid; 像SELECT groupid一样,MIN(???-???)作为minimum_time_diff FROM mytable GROUP BY groupid;

Any help would be appreciated! 任何帮助,将不胜感激!

One way is with a self-join and group by : 一种方法是使用自我加入并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;

You can also do this with variables: 您还可以使用变量执行此操作:

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;

This uses the observation that when the timestamps are ordered, then the minimum difference is going to occur between two adjacent rows. 这样可以观察到,当排序时间戳时,两个相邻行之间将出现最小差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM