3

Possible Duplicate:
Simulating group_concat MySQL function in MS SQL Server 2005?

I have a table tb1. I want concatenated result set.

enter image description here

Please help me by writing a query for this problem?

Community
  • 1
  • 1
RAKESH HOLKAR
  • 2,127
  • 5
  • 24
  • 42

2 Answers2

2

Here, try this one,

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

HEre's another version

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

John Woo
  • 258,903
  • 69
  • 498
  • 492
  • Note that only the inner select is required on the first example (i.e. the table used for the left join) – brichins Oct 02 '12 at 00:40
-3

Try this:

select col1 + ' ' + col2 from bla.bla.bla
Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
user1643583
  • 1
  • 1
  • 4