MySQL按时间戳分组

第666章

我需要编写mysql查询,该查询将根据时间戳之间的差异对结果进行分组。可能吗?我有带有位置的表,每行都有created_at(时间戳记),我想按差异> 1分钟对结果进行分组。例:

id | lat | lng | created_at
1. | ... | ... | 2020-05-03 06:11:35
2. | ... | ... | 2020-05-03 06:11:37
3. | ... | ... | 2020-05-03 06:11:46
4. | ... | ... | 2020-05-03 06:12:48
5. | ... | ... | 2020-05-03 06:12:52

该数据的结果应为2组(1,2,3)和(4,5)

专线小巴

这取决于您的实际需求。如果您希望将属于同一分钟的记录分组在一起,而不管与先前记录的区别,那么简单的聚合就足够了:

select 
    date_format(created_at, '%Y-%m-%d %H:%i:00') date_minute,
    min(id) min_id, 
    max(id) max_id, 
    min(created_at) min_created_at, 
    max(created_at) max_created_at,
    count(*) no_records
from mytable
group by date_minute

另一方面,如果要建立间隔小于1分钟的连续记录组,则这是一个间隙和孤岛的问题。这是使用窗口函数(在MySQL 8.0中可用)解决它的方法:

select 
    min(id) min_id, 
    max(id) max_id, 
    min(created_at) min_created_at, 
    max(created_at) max_created_at,
    count(*) no_records
from (
    select
        t.*,
        sum(case when created_at < lag_created_at + interval 1 minute then 0 else 1 end) 
            over(order by created_at) grp
    from (
        select
            t.*,
            lag(created_at) over(order by created_at) lag_created_at
        from mytable t
    ) t
) t
group by grp

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章