2012-09-03 78 views

回答

2

這裏,試試這個,

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 

SQLFiddle Demo

這裏的另一個版本

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 

SQLFiddle Demo

+0

謝謝先生幫助我。 –

+0

注意,在第一個例子中只需要內部選擇(即用於左連接的表格) – brichins

-3

試試這個:

select col1 + ' ' + col2 from bla.bla.bla 
+2

串聯的值在不同的行中。 –

相關問題