Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select multiple rows in one column [closed]

I have table TestTable

ID Name
-------
1  A
1  B
1  C 
2  D 
2  E
3  F

I want to write a query in SQL Server 2008 which will return

ID Name
----------    
1   A,B,C
2   D,E
3   F

Please someone help me to write this query.

like image 738
Gulrej Avatar asked Dec 28 '12 06:12

Gulrej


2 Answers

AFAIK, there is no native way to do so. However, you can use the FOR XML to do this like so:

SELECT 
  t1.Id,
  STUFF((
    SELECT ', ' + t2.name  
    FROM Table1 t2
    WHERE t2.ID = t1.ID
    FOR XML PATH (''))
  ,1,2,'') AS Names
FROM Table1 t1
GROUP BY t1.Id;

SQL Fiddle Demo

This will give you:

| ID |   NAMES |
----------------
|  1 | A, B, C |
|  2 |    D, E |
|  3 |       F |
like image 120
Mahmoud Gamal Avatar answered Oct 02 '22 16:10

Mahmoud Gamal


try this ::

SELECT  a.ID, 
        SUBSTRING(d.Name,1, LEN(d.Name) - 1) Name
FROM
        (
            SELECT DISTINCT ID
            FROM testTable
        ) a
        CROSS APPLY
        (
            SELECT [Name] + ', ' 
            FROM testTable AS B 
            WHERE A.ID = B.ID 
            FOR XML PATH('')
        ) D (Name)  
like image 37
Ajith Sasidharan Avatar answered Oct 02 '22 14:10

Ajith Sasidharan