Merge column data inline - SQL Server

0

I have the following situation:

Usuario_A     telefone1
Usuario_A     telefone2
Usuario_A     telefone3

How can I do that when I make a select, have the following output:

+-----------+----------------------------------+
| Usuario_A |  telefone1, telefone2, telefone3 |
+-----------+----------------------------------+

In MySQL I know I have the function GROUP_CONCAT , but for SQL Server I have not identified anything that can help me solve it.

    
asked by anonymous 08.11.2018 / 17:08

2 answers

0

Try this:

SELECT Usuario, Telefone1 [TELEFONE] FROM tbUsuario
UNION ALL
SELECT Usuario, Telefone2 [TELEFONE] FROM tbUsuario
UNION ALL
SELECT Usuario, Telefone3 [TELEFONE] FROM tbUsuario
    
08.11.2018 / 17:16
0

You can use STUFF () with FOR XML PATH

CREATE TABLE T(
  [User] VARCHAR(45),
  Phone VARCHAR(45)
);

INSERT INTO T VALUES
('Usuario_A', 'telefone1'),
('Usuario_A', 'telefone2'),
('Usuario_A', 'telefone3'),
('Usuario_B', 'telefone4');

SELECT T1.[User],
       STUFF(
              (
                SELECT ',' + T2.Phone
                FROM T T2
                WHERE T2.[User] = T1.[User]
                FOR XML PATH('')
              ), 1, 1, ''
            ) Phones
FROM T T1
GROUP BY T1.[User];

Returns:

+-----------+-------------------------------+
|   User    |            Phones             |
+-----------+-------------------------------+
| Usuario_A | telefone1,telefone2,telefone3 |
| Usuario_B | telefone4                     |
+-----------+-------------------------------+
    
09.11.2018 / 21:48