Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Concatenar uma única coluna em uma única linha no SQL Server Management Studio


Dados de teste
DECLARE @t TABLE ([StopNumber] INT, [DumpsterNumber] VARCHAR(10))
INSERT INTO @t
VALUES
(1,'245'),
(1,'248'),
(2,'312'),
(2,'314'),
(2,'316')

Consulta
SELECT t.[StopNumber] 
       ,STUFF((SELECT ', ' + [DumpsterNumber]
              FROM TestTableOne
              WHERE [StopNumber] = t.StopNumber
              FOR XML PATH(''), TYPE
               ).value('.', 'varchar(max)'), 1, 2, '') AS [DumpsterNumber]
FROM TestTableOne t
GROUP BY t.[StopNumber]

Conjunto de resultados
╔════════════╦════════════════╗
║ StopNumber ║ DumpsterNumber ║
╠════════════╬════════════════╣
║          1 ║ 245, 248       ║
║          2 ║ 312, 314, 316  ║
╚════════════╩════════════════╝