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

Come posso concatenare e creare un gruppo di testo nel server sql?

Ecco, prova questo,

SELECT  a.dept_id, 
        NewTable.NameValues
FROM    (
          SELECT DISTINCT dept_ID
          FROM tableA
        ) a 
        LEFT JOIN
        (
          SELECT  dept_id,
                STUFF((
                  SELECT  ', ' + [Name] 
                  FROM    tableA
                  WHERE   ( dept_id = Results.dept_id )
                  FOR XML PATH('')), 1, 1, '') AS NameValues
          FROM    tableA Results
          GROUP BY dept_id
        ) NewTable
        on a.dept_id = NewTable.dept_id
GO

Demo SQLFiddle

Ecco un'altra versione

SELECT  a.dept_id, 
        SUBSTRING(d.nameList,1, LEN(d.nameList) - 1) ConcatenateNames
FROM 
        (
            SELECT DISTINCT dept_id
            FROM   tableA
        ) a
        CROSS APPLY
        (
            SELECT name + ', ' 
            FROM tableA AS B 
            WHERE A.dept_id = B.dept_id 
            FOR XML PATH('')
        ) D (nameList)
GO

Demo SQLFiddle