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

Acumulando várias linhas em uma única linha


Basta usar o mesmo método para as outras colunas:
SELECT
    t.Department,
    Worker = 
        STUFF((
            SELECT ';' + Worker
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N''),
    Phone = 
        STUFF((
            SELECT ';' + Phone
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N''),
    Ext = 
        STUFF((
            SELECT ';' + Ext
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N'')
FROM tbl t
GROUP BY t.Department