我有一个如下形式的 mysql 表:
- 时间戳(unix 时间戳)
- 一些值列[...]
- 组ID
现在我想构建一个查询,该查询按 groupid 分组并打印组中每个时间戳之间的最小时间差。
类似于 SELECT groupid, MIN(??? - ???) asminimum_time_diff FROM mytable GROUP BY groupid;
如有任何帮助,我们将不胜感激!
最佳答案
一种方法是使用自连接和分组依据
:
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;
这使用了这样的观察:当时间戳排序时,两个相邻行之间将出现最小差异。
关于mysql - 获取每组中元素之间的最小差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21414366/