• ChrisM@Work (3/7/2013)


    This is called "Islands and Gaps". An island is a set of rows where the dates are consecutive, bounded by rows with non-consecutive dates. Jeff Moden has a great Spackle article [/url]covering the subject in some detail. Once you've identified the islands, what do you want to do?

    Edit: clarity

    That's a great article Chris! Oldey but goody.

    Makes me think of something like this. 😛

    WITH SampleData AS (

    SELECT Name, RecordedDate

    FROM (

    Values ('John', dateadd(day,1,GetDate()))

    ,('John', dateadd(day,2,GetDate()))

    ,('John', dateadd(day,3,GetDate()))

    ,('John', dateadd(day,6,GetDate()))

    ,('John', dateadd(day,7,GetDate()))

    ,('John', dateadd(day,8,GetDate()))

    , ('John', dateadd(day,12,GetDate()))

    ,('John', dateadd(day,13,GetDate())))a (Name, RecordedDate))

    SELECT Name, COUNT(*)

    FROM (

    SELECT Name

    FROM (

    SELECT Name, RecordedDate

    ,rn=RecordedDate-ROW_NUMBER() OVER (PARTITION BY Name ORDER BY RecordedDate)

    FROM SampleData) a

    GROUP BY Name, rn) b

    GROUP BY Name

    Although I couldn't think of a good name for the second column. [Count of islands] perhaps?


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St