create table dbo.AgentLog ( AgentID int ,LogInTime datetime ,LogOutTime datetime ) go insert dbo.AgentLog select 1, '2010-09-08 09:40:00.000', '2010-09-08 10:14:00.000' union all select 1, '2010-09-08 10:35:00.000', '2010-09-08 12:04:00.000' union all select 1, '2010-09-08 13:11:00.000', '2010-09-08 14:24:00.000' union all select 1, '2010-09-08 14:35:00.000', '2010-09-08 16:08:00.000' union all select 2, '2010-09-08 09:00:00.000', '2010-09-08 09:23:00.000' union all select 2, '2010-09-08 10:12:00.000', '2010-09-08 12:05:00.000' union all select 2, '2010-09-08 13:12:00.000', '2010-09-08 15:07:00.000' union all select 2, '2010-09-08 15:10:00.000', '2010-09-08 16:25:00.000' go ;with AgentLogCTE as (select Row_Number() over (partition by AgentID order by LogInTime) as RowID, * from dbo.AgentLog ) select * from AgentLogCTE go ;with AgentLogCTE as (select Row_Number() over (partition by AgentID order by LogInTime) as RowID, * from dbo.AgentLog ) select t1.AgentID ,t2.LogOutTime as PrevLogout ,t1.LogInTime as Login ,convert(varchar, t1.LogInTime - t2.LogOutTime, 108) as BreakTime from AgentLogCTE t1 join AgentLogCTE t2 on t2.RowID = (t1.RowID-1) and t1.AgentID = t2.AgentID go drop table dbo.AgentLog go