MySQL分组的时间戳差异

问题描述 投票:0回答:1

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

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)

mysql sql date group-by gaps-and-islands
1个回答
0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.