首页 > 解决方案 > SQL 中两个连续事件之间的平均时间

问题描述

我有一个如下所示的表格。

时间 事件
2021-03-19T17:15:05 一个
2021-03-19T17:15:11
2021-03-19T17:15:11 C
2021-03-19T17:15:12 一个
2021-03-19T17:15:14 C

我想找到事件 A 与其之后的事件之间的平均时间。如何使用 SQL 查询找到它?这里所需的输出是:4 秒。我非常感谢您能提供的任何帮助。

标签: sqlapache-spark-sqltimestamp

解决方案


基本思想是lead()从下一行获取时间。然后你需要计算差异。所以对于所有行:

select t.*,
       (to_unix_timestamp(lead(time) over (order by time) -
        to_unix_timestamp(time)
       ) as diff_seconds
from t;

使用子查询和过滤来获取A平均值:

select avg(diff_seconds)
from (select t.*,
             (to_unix_timestamp(lead(time) over (order by time) -
              to_unix_timestamp(time)
             ) as diff_seconds
      from t
     ) t
where event = 'A';

推荐阅读