Set based query to group data ordered data
Start by making a column like CASE WHEN MinutesSinceLastRequest &lt; 20 THEN 0 ELSE 1 END AS IsOver20

Then wrap that in a rolling sum - this will change every time there's a 1 for IsOver20: SUM(IsOver20) OVER (ORDER BY [TimeStamp] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS GroupNum

So now you can group by this easily. Include PARTITION BY UserId if you need to break it down by UserId too.