• Or if you want all months within the range (not just the ones where the counts change), you can do this:

    WITH SampleData (AccountNo, OpenDate, CloseDate) AS(

    SELECT 1361677, '20121203', '20140102'

    UNION ALL SELECT 1361771, '20121205', '20130219'

    UNION ALL SELECT 1362409, '20121205', '20130117'

    UNION ALL SELECT 1380003, '20121219', '20130108'

    UNION ALL SELECT 1381801, '20121222', '20130129'

    UNION ALL SELECT 1381181, '20121222', '20130715'

    UNION ALL SELECT 1388490, '20121224', '20130715'

    UNION ALL SELECT 1388637, '20121224', '20130705'

    UNION ALL SELECT 1388718, '20121224', '20130715'

    UNION ALL SELECT 1377409, '20121224', '20130108'

    UNION ALL SELECT 1362215, '20121224', '20130715'

    ),

    Tally (n) AS

    (

    SELECT TOP

    (

    SELECT 1+MAX(DATEDIFF(month, 0, CloseDate)-DATEDIFF(month, 0, OpenDate))

    FROM SampleData

    )

    ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

    FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)

    CROSS JOIN (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)

    )

    SELECT YearMonth, TotalAccounts=COUNT(CASE WHEN LEFT(CloseDate, 6) <> YearMonth THEN 1 END)

    FROM SampleData a

    CROSS APPLY

    (

    SELECT YearMonth=CONVERT(VARCHAR(6), DATEADD(month, n-1, OpenDate), 112)

    FROM Tally

    WHERE n BETWEEN 1 AND 1+DATEDIFF(month, 0, CloseDate)-DATEDIFF(month, 0, OpenDate)

    ) b

    GROUP BY YearMonth

    ORDER BY YearMonth;


    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