Skip to content
Advertisement

SQL Server – group by with row number – Gaps and Islands

I have a table with data like this

I need to create a view on top of this table to have data formatted in the below format for the Flag, basically the duration for which the Flag was Y or N. (EndDateSID – 0 is currently active, so today’s date)

Most customers only have a change in their Flag once, hence below query works:

How can I achieve the intended output for customers like the one above, having changes in the flag more than once?

Advertisement

Answer

This is a gaps and islands problem. You need to use ROW_NUMBER() to identify your gaps, so the start stage would be:

Output:

The key here is that by taking the row number of each row, and also the row number of each row withing the group, you can get a unique identifier (GroupID + MarketingOptIn) which identifies each of your islands. Then it is just a case of grouping by this identifier when doing your aggregates:

FULL WORKING EXAMPLE

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement