• My personal preference is to do this with a CROSS APPLY:

    WITH SampleData AS (

    SELECT RowID, DateStamp=CAST(DateStamp AS DATE), PrevStatus, CurrentStatus

    FROM (VALUES

    (1, '6/1/2012', NULL, 8),

    (2, '6/2/2012', 8, 9),

    (3, '6/8/2012', 9, 8),

    (4, '6/10/2012', 8, 9),

    (5, '6/12/2012', 9, 8),

    (6, '6/16/2012', 8, 9),

    (7, '6/19/2012', 9, 8)) a(RowID, DateStamp, PrevStatus, CurrentStatus))

    SELECT a.RowID, a.DateStamp, PrevStatus, CurrentStatus

    ,ElapsedDays=DATEDIFF(day, b.DateStamp, a.DateStamp)

    FROM SampleData a

    CROSS APPLY (

    SELECT TOP 1 DateStamp

    FROM SampleData b

    WHERE a.CurrentStatus = b.CurrentStatus AND b.DateStamp < a.DateStamp

    ORDER BY b.DateStamp DESC) b

    WHERE a.CurrentStatus = 8

    ORDER BY a.RowID;

    At least it would have been in SQL versions earlier than 2012. TheSQLGuru's solution for SQL 2012 is probably faster. Haven't had the chance to test it yet myself as I just got 2012 this week. Soon though.


    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