31

My T-SQL query generates following result set

ID        Date
756 2011-08-29
756 2011-08-31
756 2011-09-01
756 2011-09-02

How can I convert like this

ID                Date
756 2011-08-29, 2011-08-31, 2011-09-01, 2011-09-02

Any suggestion would be appreciated.

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
poshan
  • 2,621
  • 4
  • 19
  • 30

1 Answers1

79

You could use FOR XML PATH and STUFF to concatenate the multiple rows into a single row:

select distinct t1.id,
  STUFF(
         (SELECT ', ' + convert(varchar(10), t2.date, 120)
          FROM yourtable t2
          where t1.id = t2.id
          FOR XML PATH (''))
          , 1, 1, '')  AS date
from yourtable t1;

See SQL Fiddle with Demo

Taryn
  • 234,956
  • 54
  • 359
  • 399
  • 5
    This gave me a starting space character. I fixed it by changing `, 1, 1, '') AS date` to `, 1, 2, '') AS date`. – voidstate Aug 01 '17 at 14:57