sql - 计算事件 A 和 B 之间的最短时间差,仅当事件 B 发生在事件 A 之后
问题描述
对于特定的user_id:如果发生事件A,有时会发生事件B,有时不会发生。但是,如果事件 B 发生,则计算事件 A 和 B 之间的最短时间差。
+-----------+----------+-------------+---------------+
| event_id | user_id | timestamp |
+-----------+----------+-------------+---------------+
| A | 1 | January, 01 2021 10:40:00 |
| B | 1 | January, 01 2021 14:40:00 |
| A | 1 | January, 04 2021 13:30:00 |
| A | 1 | January, 04 2021 19:30:00 |
| A | 1 | January, 05 2021 13:40:00 |
| B | 1 | January, 05 2021 16:40:00 |
+-----------+----------+-------------+---------------+
此处,对于用户 =1:2021 年 1 月 1 日:BA = 4 小时,对于 2021 年 1 月 5 日:BA = 3 小时
如何在 MySQL 或 Excel 中实现这一点?
解决方案
我会使用窗口函数:
select user_id,
min( next_b_timestamp - timestamp ) as shortest_ab_duration
from (select t.*,
min(case when event_id = 'B' then timestamp end) over (partition by user_id order by timestamp desc) as next_b_timestamp
from t
) t
where event_id = 'A'
group by user_id;
SQL Server 可能不会接受:
min( next_b_timestamp - timestamp ) as shortest_ab_duration
相反,您可以使用:
min( datediff(minute, timestamp, next_b_timestamp) ) as shortest_ab_duration_minutes
推荐阅读
- bash - 如何使用 lxc exc 以特定用户身份发出多个命令
- r - 使用正则表达式替换区分大小写的断字
- react-native - React Native Redux - 登录后重定向
- r - 从R中的2个因子制作1个因子
- angular - 如何修复预期 $.length = 2 等于 1
- python - 寻求有关用于从外部“.py”文件动态导入函数的代码的建议
- javascript - cv.Mat 不是构造函数 opencv
- reactjs - 如何根据服务器调用制作动态表单
- python - 如何将多个 CSV 文件从目录导出到另一个 CSV 文件表
- c# - C# 查找两个通用列表之间的变化