• I agree that your expected results are wrong because you have an enddate greater than the startdate and that will generate a problem in the next row (rows 3 & 4).

    This might give you an idea of what you need to solve your problem, even if I don't understand your "First Date" parameter.

    WITH CTE AS(

    SELECT *,

    ROW_NUMBER() OVER( PARTITION BY id, YEAR(StartDate) ORDER BY startdate) rn,

    YEAR(StartDate) DateYear

    FROM #table

    )

    SELECT c1.id,

    c1.cid,

    c1.startdate,

    ISNULL( c2.startdate - 1, CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, 0, c1.startdate) + 1, 0) < GETDATE()

    THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, c1.startdate) + 1, 0) END)

    FROM CTE c1

    LEFT

    JOIN CTE c2 ON c1.DateYear = c2.DateYear

    AND c1.id = c2.id

    AND c1.rn = c2.rn - 1

    ORDER BY c1.id, c1.startdate DESC

    EDIT: Code Formatting.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2