Something like this?declare @freq table (ActionDateTime datetime, Action varchar(50), ClientID varchar(50))insert @freq select '20091216 08:55:45.554', 'Arrive', 'abc'union all select '20091216 14:25:33.519', 'Leave', 'abc'union all select '20091216 08:55:45.554', 'Arrive', 'xyz'union all select '20091216 14:25:33.519', 'Leave', 'xyz'union all select '20091216 15:55:45.554', 'Arrive', 'abc'union all select '20091216 16:25:33.519', 'Leave', 'abc'union all select '20091217 15:55:45.554', 'Arrive', 'abc'union all select '20091217 16:25:33.519', 'Leave', 'abc'select a.ClientID, b.ActionDay, datediff(minute, max(case when Action = 'Arrive' then ActionDateTime end), max(case when Action = 'Leave' then ActionDateTime end)) as FirstStayDurationInMinutesfrom @freq a inner join ( select ClientID, ActionDay, min(ActionDateTime) as FirstLeave from ( select *, dateadd(day, datediff(day, '19000101', ActionDateTime), '19000101') as ActionDay from @freq) a where Action = 'Leave' group by ClientID, ActionDay) b on a.ClientID = b.ClientID and ActionDateTime between ActionDay and FirstLeavegroup by a.ClientID, b.ActionDay
Ryan Randall - Yak of all tradesSolutions are easy. Understanding the problem, now, that's the hard part.