我正在关注此人的教程“ How to Use Values from Previous or Next Rows in a SQL Server Query”。
这是他正在使用的主要查询:
;WITH UserActivityWRowNum(RowNumber, User, Activity, ActivityTime, ActivityDate)
AS
(
SELECT ROW_NUMBER()OVER(ORDER BY user, ActivityTime) RowNumber
,User
,Activity
,ActivityTime
,CAST(ActivityTime as DATE) as ActivityDate
FROM dbo.UserActivity
SELECT LogOns.User, LogOns.ActivityDate
,LogOffs.ActivityTime LogOff
,LogOns.ActivityTime LogOn
, DATEDIFF(minute, LogOffs.ActivityTime, LogOns.ActivityTime) IdleTime
FROM (SELECT * FROM UserActivityWRowNum WHERE Activity='LogOn') LogOns
JOIN (SELECT * FROM UserActivityWRowNum WHERE Activity='LogOff') LogOffs
ON LogOffs.RowNumber=LogOns.RowNumber - 1
AND LogOffs.User - LogOns.User
AND LogOffs.ActivityDate - LogOns.ActivityDate
我试图说明用户在两天之间会有登录/注销周期的天数。这使得很难计算每天的总空闲时间。 从本质上讲,我该如何考虑跨越两天的注销/登录周期并给出特定一天的总闲置时间?每个用户每天的总空闲时间是链接中所述的预期输出
例如,下图显示了第6行的注销活动。因此,从技术上讲,该用户在该天的剩余7个小时(2013-01-01)中处于空闲状态。 2013-01-02将有一个虚拟注销作为显示为2013-01-02 00:00:00的第一项