how can I concatenate records from the same column in sql server?

0

If you could help me, I have a table like this:

identificativo        fecha
72028586            11/05/2018
72028586            13/05/2018
72045976            17/05/2018
72063798            13/05/2018

and I need to make a query to show me the table like this:

identificativo        fecha
72028586           11/05/2018, 13/05/2018
72045976           17/05/2018
72063798           13/05/2018

How do I do it ????

    
asked by Andy Montalvo 21.05.2018 в 18:07
source

1 answer

1

It seems that the function you're looking for is STRING_AGG

SELECT 
  identificativo, STRING_AGG(fecha, ',') 
FROM Table1 
GROUP BY identificativo;

For versions previous to SQL server 2017 we use the trick of for xml

SELECT identificativo, fecha=STUFF(
  (SELECT ', ' + fecha AS [text()]
        FROM Table1 XT
        WHERE XT.identificativo = T.identificativo
        FOR XML PATH('')), 1, 2, '') 
FROM Table1 T 
GROUP BY identificativo;

ref: link

To put aside the space behind the comma, you change these two lines

 (SELECT ',' + fecha AS [text()]

...

    FOR XML PATH('')), 1, 1, '') 
    
answered by 21.05.2018 в 18:20