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
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
2条答案
按热度按时间cigdeys31#
不幸的是,SQLServer不支持窗口函数中的日期范围规范。我建议在这里进行横向连接:
子查询将在3分钟内为同一行带来最新的行
user_id
(或空结果集,如果在该时间段内没有行)。然后可以在外部查询中使用该信息来显示相应的timestamp
,并计算与当前值的差值。ukxgm1gy2#
只需计算当前时间和延迟时间戳的差值,如果超过3分钟,则返回null: