• Use the following query

    select @cols = STUFF((SELECT ',' + QUOTENAME(Date)

    FROM #distinctDate

    Order by [year], MonthNumber

    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''

    )

    I have remove the distinct, if you want to distinct the record to it when you create the #distinctDate

    after that i have added the order by clause, because there is no such thing as Natural Order 😀