我有两个表来跟踪用户活动:
我需要编写一个SQL查询来获取格式为
的数据: 用户ID |的UserRole | LoginTime | LogOutTime
注意:LoginTime / LogOutTime是ActivityAuditTrail表中的Activity_Time_Stamp。我无法弄清楚这个逻辑。
答案 0 :(得分:1)
;with LoginTime AS(
SELECT User_Id, Activity_Time_Stamp
FROM Activity_Audit_Trail
WHERE Activity_Id = 01
),LogOutTime AS(
SELECT ROW_NUMBER() OVER(PARTITION BY a.User_Id ORDER BY Sa.User_Id, a.Activity_Time_Stamp DESC) AS RowNumber
a.User_Id, a.Activity_Time_Stamp AS LogOutTimeValue, li.Activity_Time_Stamp AS LoginTimeValue
FROM Activity_Audit_Trail a
JOIN LoginTime li
ON li.User_Id = a.User_Id
WHERE Activity_Id = 02
AND a.Activity_Time_Stamp > li.Activity_Time_Stamp
)
Select User_Id
,User_Role
,LoginTimeValue
,LogOutTimeValue
FROM LogOutTime
WHERE RowNumber = 1
请试试这个..因为我没有表格的架构脚本,没有经过测试。您可能会遇到一些语法错误。请遵循逻辑..
答案 1 :(得分:1)
尝试对ActivityAuditTrail
用户,角色和会话令牌中的行进行分组,然后分别选择最低和最高活动时间戳作为登录和注销时间戳:
SELECT User_Id, User_Role, MIN(Activity_Time_Stamp) AS LoginTime, CASE COUNT(*) WHEN 2 THEN MAX(Activity_Time_Stamp) ELSE NULL END AS LogOutTime
FROM ActivityAuditTrail
GROUP BY User_Id, User_Role, User_Session
此查询将为您提供每个用户会话的登录和注销时间戳。
答案 2 :(得分:1)
我认为你不需要你的活动表。 如果用户仅登录和退出系统一次,此查询将为您提供所需的信息:
Select AT.UserId. AT.UserRole, MIN(Activity_Time_Stamp) as LoginTime, MAX(Activity_Time_Stamp) as LogoutTime
from ActivityAuditTrail AT
group by AT.UserId. AT.UserRole
当然这还不够,所以你需要一种方法来通过注销对登录进行分组。 我假设这是Activity_ID字段的用途。因此,每个活动都由几个活动审计跟踪组成,其中第一个是登录,最后一个是注销 在这种情况下,你可以运行:
Select AT.UserId. AT.UserRole, AT.Activity_ID, MIN(Activity_Time_Stamp) as LoginTime, MAX(Activity_Time_Stamp) as LogoutTime
from ActivityAuditTrail AT
group by AT.UserId. AT.UserRole, AT.Activity_ID
编辑:
select distinct AT.UserId, AT.UserRole,
(select Activity_Time_Stamp from ActivityAuditTrail where UserId=AT.UserId and Activity_ID=1) as LoginTime,
(select Activity_Time_Stamp from ActivityAuditTrail where UserId=AT.UserId and Activity_ID=2) as LogoutTime
from ActivityAuditTrail AT
答案 3 :(得分:1)
SELECT User_Id, User_Role, Activity_Time_Stamp AS LoginTime,
( SELECT Activity_Time_Stamp
FROM ActivityAuditTrail aud2
WHERE aud2.Activity_Id=2
AND ActivityAuditTrail.User_Id=aud2.User_Id
AND ActivityAuditTrail.User_Session=aud2.User_Session
) AS LogOutTime
FROM ActivityAuditTrail
WHERE Activity_Id=1
我是安全的,并假设会话不是用户唯一的,但如果他们是,你可以完全从WHERE中省略user_id。
答案 4 :(得分:0)
SELECT b.UserId, b.User_Role MIN(b.Activity_Time_Stamp) AS LoginTime, MAX(b.Activity_Time_Stamp) AS LogoutTime
FROM `Activity` a
INNER JOIN `Activity Audit Trail` b ON a.Id = b.Activity_Id
GROUP BY b.User_Id
答案 5 :(得分:0)
如何识别整个会话,我的意思是,用户可能已多次登录并注销,如何知道哪个LogOut匹配哪个登录。