create table tb
(
[user] varchar(20),
operate varchar(20),
[time] datetime
)
insert into tb
select 'LiMing', 'Login', '2010/10/24 8:03' union all
select 'WangYi', 'Login', '2010/10/24 8:14' union all
select 'WangYi', 'Logout', '2010/10/24 16:14' union all
select 'LiMing', 'Logout', '2010/10/24 16:44'
select a.[user] , cast(DATEdiff(MI, b.[time] ,a.[time] )/ 60 as varchar) + ':' + cast(DATEdiff(MI, b.[time] ,a.[time] )%60 as varchar) AS 在线时间 from (
select * from tb where operate ='Logout') a,
(select * from tb where operate ='Login') b
where a.[user] =b.[user]
------解决方案--------------------
------解决方案-------------------- with tb as ( select 'LiMing' [User] ,'Login' operate ,convert(datetime,'2010/10/24 8:03') [time] union all select 'WangYi' ,'Login' ,convert(datetime,'2010/10/24 8:14') union all select 'WangYi' ,'Logout' ,convert(datetime,'2010/10/24 8:22')union all select 'LiMing' ,'Logout' ,convert(datetime,'2010/10/24 16:44') union all select 'WangYi' ,'Login' ,convert(datetime,'2010/10/25 8:14') union all select 'WangYi' ,'Logout' ,convert(datetime,'2010/10/25 16:14') ) ,tb2 as ( select * ,ROW_NUMBER() over(order by [user],[time]) as id from tb ) select * ,(select CONVERT(nvarchar(50), DATEDIFF(MI,t.[time],[time])/60) +':' +CONVERT(nvarchar(50), DATEDIFF(MI,t.[time],[time])%60) from tb2 where id=t.id+1) [在线时间/秒] from tb2 t where t.operate='Login' and exists(select * from tb2 where id=t.id+1 and t.[User]=[User] and t.operate<>operate)