sql >> Base de Datos >  >> RDS >> Sqlserver

Concatenar una sola columna en una sola fila en SQL Server Management Studio

Datos de prueba

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  ║
╚════════════╩════════════════╝