MySQL 具有分层数据的连续行的时间差

标签 mysql

如何查询具有分层数据的连续行之间的时间差?例如,我想从下表中选择:

+-------+----------+---------------------+
| group_id |  event   |     event_time      |
+-------+----------+---------------------+
|     1 | alarm    | 2016-12-01 17:53:12 |
|     1 | alarm    | 2016-12-01 17:59:43 |
|     2 | purchase | 2016-11-29 09:49:47 |
|     2 | purchase | 2016-11-29 09:53:51 |
|     2 | purchase | 2016-11-29 09:57:59 |
|     2 | alarm    | 2016-11-29 10:01:02 |
|     2 | alarm    | 2016-11-29 10:13:27 |
|     2 | purchase | 2016-11-29 10:15:00 |
|     2 | purchase | 2016-11-29 10:16:24 |
+-------+----------+---------------------+

至:

+-------+----------+---------------------+------------+
| group_id |  event   |     event_time      | time_delta |
+-------+----------+---------------------+------------+
|     1 | alarm    | 2016-12-01 17:53:12 | 0          |
|     1 | alarm    | 2016-12-01 17:59:43 | 00:06:31   |
|     2 | purchase | 2016-11-29 09:49:47 | 0          |
|     2 | purchase | 2016-11-29 09:53:51 | 00:04:04   |
|     2 | purchase | 2016-11-29 09:57:59 | 00:04:08   |
|     2 | alarm    | 2016-11-29 10:01:02 | 0          |
|     2 | alarm    | 2016-11-29 10:13:27 | 00:12:25   |
|     2 | purchase | 2016-11-29 10:15:00 | 0          |
|     2 | purchase | 2016-11-29 10:16:24 | 00:01:24   |
+-------+----------+---------------------+------------+

以上数据仅供引用;我的数据实际上有很多组和很多事件。所以基本上,我想计算连续行中的 group_id 和事件相同时的时间差。

最佳答案

您可以通过执行以下操作获取给定组的上一次时间:

select t.*,
       (select t2.time_delta
        from t t2
        where t2.group_id = t.group_id and
              t2.event = t.event and
              t2.event_time < t.event_time
        order by t2.event_time desc
        limit 1
       ) as prev_event_time
from t;

然后您可以通过多种方式获取时差,例如:

select t.*, timediff(event_time, prev_event_time)
from (select t.*,
             (select t2.time_delta
              from t t2
              where t2.group_id = t.group_id and
                    t2.event = t.event and
                    t2.event_time < t.event_time
              order by t2.event_time desc
              limit 1
             ) as prev_event_time
      from t
     ) t

关于MySQL 具有分层数据的连续行的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498534/

相关文章:

mysql - 条件 UNIQUE/FK 约束

mysql 字段 'col1' 没有默认值

php - 如何确保特定帖子的用户仅点击一次我的投票链接?

mysql - jsp sql更新查询

mysql - 截断 SQL 数据库中的几乎所有表

mysql - SQL查询不知道变量

mysql - 备份MYSQL的应用程序

php - 多次点击按钮 - PHP

c# - 将 DateTime.Ticks 值转换为 SQL 日期的 MySQL 脚本

PHP 从 Firebird 获取数据