How to find the boundaries of groups of contiguous sequential numbers?

As mentioned in the comments this is a classic gaps and islands problem. A solution popularized by Itzik Ben Gan is to use the fact that ROW_NUMBER() OVER (ORDER BY number) – number remains constant within an “island” and cannot appear in multiple islands. WITH T AS (SELECT ROW_NUMBER() OVER (ORDER BY number) – number … Read more

SQL count consecutive days

This is a Gaps and Islands problem. The easiest way to solve this is using ROW_NUMBER() to identify the gaps in the sequence: SELECT UserName, UserDate, UserCode, GroupingSet = DATEADD(DAY, -ROW_NUMBER() OVER(PARTITION BY UserName ORDER BY UserDate), UserDate) FROM UserTable; This gives: UserName | UserDate | UserCode | GroupingSet ————+—————+————+————- user1 | 09-01-2014 | 1 … Read more