为与用户id匹配的上一条记录自引用表

wj8zmpe1  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(592)

我试图找到从sql数据计算周期时间的最简单方法。在数据源中,我有唯一的站点id、用户id和日期/时间戳,以及它们正在执行的其他数据。
我要做的是将表连接到它自己,以便对于我得到的每个日期/时间戳:-该用户id的最新上一个示例在3分钟内的日期/时间戳或null-这两个戳之间的差异(周期时间=记录之间的时间量)
这应该很简单,但我不能把我的大脑。有什么帮助吗?

cigdeys3

cigdeys31#

不幸的是,SQLServer不支持窗口函数中的日期范围规范。我建议在这里进行横向连接:

select 
    t.*, 
    t1.timestamp last_timestamp, 
    datediff(second, t1.timestamp, t.timestamp) diff_seconds
from mytable t
outer apply (
    select top(1) t1.*
    from mytable t1
    where 
        t1.user_id = t.user_id 
        and t1.timestamp >= dateadd(minute, -3, t.timestamp)
        and t1.timestamp < t.timestamp
    order by t1.timestamp desc
) t1

子查询将在3分钟内为同一行带来最新的行 user_id (或空结果集,如果在该时间段内没有行)。然后可以在外部查询中使用该信息来显示相应的 timestamp ,并计算与当前值的差值。

ukxgm1gy

ukxgm1gy2#

只需计算当前时间和延迟时间戳的差值,如果超过3分钟,则返回null:

with cte as
 (
   select 
      t.*
     ,datediff(second, timestamp, lag(timestamp) over (partition by user_id order by timestamp) as diff_seconds
   from mytable as t
 )
select cte.*
  ,case when diff_seconds <= 180 then diff_seconds end
from cte

相关问题