22,209
社区成员
发帖
与我相关
我的任务
分享
[code=sql]
declare @tableid int --假设一个tableid
--假设status=0 则为离线状态,status=1 则为登录状态,
;with cte_a(
select * from [t_record] where (logoutTime between startTime and endTime) and tableid=@tableid and status=0
)
--分类取最后一条记录
,cte_b as(
select max(ID) ID,用户ID from cte_a
group by 用户ID
)
--查询该时间段内登录状态的用户id
,cte_c as(
select userid from [t_record] where (loginTime between startTime and endTime) and tableid=@tableid and status=1
)
--结果
select * from [t_record] where ID in (select ID from cte_b) and userid not in (select userid from cte_c)
[/code]
---丢了两句,自己加上。。,具体数值自己改
declare @tableid int --假设一个tableid
declare @status int --假设status=0 则为离线状态
set @tableid =1 ---这个加上
set @status=0 ---这个也加上
--首先明确一下,假设你的表有自动加1的ID字段;
--其次,每次登陆,都能正常退出;登陆一次就添加一次数据;
--第二次登陆的表ID大于第一次登陆的ID;
--第N次的退出时间 小于 第N+1次的登陆时间;
--只需要查询退出时间在你的时间段内就可以了。
--1、先查询 符合时间段的数据
declare @tableid int --假设一个tableid
declare @status int --假设status=0 则为离线状态
;with cte_a(
select * from [t_record] where ([loginTime] between [startTime] and [endTime] and [tableid]=@tableid and [status]=@status)
)
--分类取最后一条记录
,cte_b as(
select max(ID) ID,用户ID from cte_a
group by 用户ID
)
--最终查询
select * from [t_record] where ID in (select ID from cte_b)
---这样写比较明了了,
---