如何在MySQL表中汇总连续行

时间:2018-05-30 13:59:47

标签: mysql sql database

所以我有一张表来跟踪建筑物内多个用户的移动情况。列显示用户的ID,他们所在的房间以及在该房间中找到他们的时间戳。该表如下所示:

user_id  location  time                
-------  --------  -------------------   
1        room1     2018-05-18 03:20:00     
1        room1     2018-05-18 03:21:15
1        room2     2018-05-18 03:22:07
2        room1     2018-05-18 03:24:20     
2        room1     2018-05-18 03:27:55
2        room1     2018-05-18 03:29:09      
1        room2     2018-05-18 03:32:37    
1        room1     2018-05-18 03:34:41
1        room1     2018-05-18 03:39:28

我要做的是总结每个房间每个用户多长时间的信息,如下所示:

user_id  location  duration(s)
-------  --------  -----------
1        room1     75
2        room1     289
1        room2     630
1        room1     287

有没有办法用一个查询来做到这一点?

2 个答案:

答案 0 :(得分:4)

您可以使用变量或相关子查询来处理此问题。变量通常更有效:

select user_id, location, min(time), max(time),
       timestampdiff(second, min(time), max(time)) as duration
from (select t.*,
             (@grp := if(@ul = concat_ws(':', user_id, location), @grp,
                         if(@ul := concat_ws(':', user_id, location), @grp + 1, @grp + 1)
                        )
             ) as grp
      from (select t.*
            from t
            order by user_id, time
           ) t cross join
           (select @ul := '', @grp := 0) params
     ) t
group by user_id, location, grp;

Here是一个带有工作代码的SQL小提琴。

答案 1 :(得分:0)

如果您使用的是MySQL 8.0 ,您可以使用窗口函数轻松解决此问题:

;WITH GroupedTable AS (
   SELECT user_id, location, time,
          ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY time) - 
          ROW_NUMBER() OVER (PARTITION BY user_id, location ORDER BY time) AS grp
   FROM mytable
)
SELECT user_id, location, TIMESTAMPDIFF(SECOND, MIN(time), MAX(time)) AS duration
FROM GroupedTable  
GROUP BY user_id, location, grp