• Lynn Pettis (4/5/2013)


    If you have duplicate dates, this fails. You will want to change RANK() to ROW_NUMBER().

    Good catch Lynn. But I don't think just changing to ROW_NUMBER fixes the tie-break problem. It just returns one row and who knows what the tie-breaker is? So whether using RANK, ROW_NUMBER, or perhaps DENSE-RANK, I should have added a tie-breaker to the ORDER BY like this:

    RANK() OVER (ORDER BY EndDate DESC, ID DESC) AS [Rank]

    This would give the tie-break to the most recently added row...but other ways of breaking the tie might be better such as a full DATETIME2 date.