Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Concatenazione di una singola colonna in una singola riga in SQL Server Management Studio

Dati di prova

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

Interroga

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]

Set di risultati

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