Sql-server – Aggregating date in one column

aggregatedatesql server

For a purpose of reporting I need to present data from table:
table A (column1, column2, date1, date2, date3,…,dateN)

My query need to present all dates in one column separated with # .

(YYYY-MM-DD# YYYY-MM-DD#..)

But problem is that number of date columns is not fixed, because from product to product can be different number of dates.

Any idea ?

Best Answer

I'm was thinking about some ugly query such as:

select isnull(convert(varchar(8), date1, 121),'') 
        + isnull('#'+convert(varchar(8), date2, 121),'')
        + isnull('#'+convert(varchar(8), date3, 121),'')
        ...
        + isnull('#'+convert(varchar(8), dateN, 121),'')
from A

But we could do better using something like:

select cast((
       select (
              select '#'+T2.N.value('./text()[1]',  'varchar(max)')
              from (
                   select T.*
                   for xml path(''), type
                   ) as T1(N)
                cross apply T1.N.nodes('/*') as T2(N)
              for xml path(''), type
              ).value('substring(./text()[1], 2)',  'varchar(max)')
       for xml path(''), type
       ) as varchar(max))
from A as T