sql - 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 秒。我非常感谢您能提供的任何帮助。
解决方案
基本思想是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';
推荐阅读
- javascript - 如何将此选定的文本放入DIV而不是textarea,并将所有选定的部分一一收集到div中
- python-3.x - 基于匹配字符串从更大的列表列表中提取子列表项
- linux - 是否可以在本地网络机器上拥有用户友好的 IP 地址?
- flutter - 我总是在颤抖中导航到空白页面
- regex - 正则表达式如何匹配[]中的任何空格
- css - 使用 Parcel bundler 构建时如何防止组合 CSS 规则?
- shiny-reactivity - 根据闪亮的输入更新表列中的值
- css - 当我在 Chrome 和 IE 上打印时如何修复和重复每个页面底部的内容
- javascript - axios.post 未从服务器返回数据:“无法解构‘(中间值)’的属性‘数据’,因为它未定义”
- ubuntu - 代理密钥 RSA SHA256:返回的签名类型不正确