首页 > 解决方案 > 计算事件 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 中实现这一点?

标签: sqlexcel

解决方案


我会使用窗口函数:

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

推荐阅读