我正在试图找到从SQL数据中计算循环时间的最简单方法。在数据源中,我有唯一的站点ID、用户ID和日期/时间戳,以及他们正在执行的其他数据。
我想要做的是将表连接到自己,以便对于我得到的每个日期/时间戳:-最近一个用户ID实例的日期/时间戳在3分钟内或为null --这两个时间戳之间的差异(循环时间=记录之间的时间量)
这应该很简单,但我不能把我的大脑围绕在这上面。有什么帮助吗?
发布于 2020-06-10 18:11:08
不幸的是,Server不支持窗口函数中的日期范围规范。我建议在这里进行横向连接:
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,并计算与当前查询的差异。
发布于 2020-06-10 18:23:55
只需计算当前时间戳和滞后时间戳的差异,如果超过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 ctehttps://stackoverflow.com/questions/62310238
复制相似问题