with hold_dates (sessionid, dateposted, commentbrief, sequence) as ( select SessionID, DatePosted, CommentBrief, ROW_NUMBER() over (order by SessionID, DatePosted asc) from ReportProcessComment with(NOLOCK) where charindex('put on hold', CommentBrief) > 0 or charindex('removed from hold', CommentBrief) > 0 ) select hd1.SessionID, dbo.GetAgeDescriptionFromSeconds(sum(datediff(second, hd1.dateposted, isnull(hd2.dateposted, getdate())))) as [HoldAgeDescription] from hold_dates hd1 left outer join hold_dates hd2 on hd2.sequence = hd1.sequence + 1 and hd2.sessionid = hd1.sessionid where charindex('removed', hd1.CommentBrief) = 0 group by hd1.SessionID