1

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

I have 2 table like this

Class table :
enter image description here

And Student Table:
enter image description here

I want to join two table but i want to have result like this
ClsName StdName
A            George
B            Jenifer,Anjel,Alex
C            Alex,Joe,Michael


how could achieve to this?
in fact for each class i want to have one row with distinct their student name

Community
  • 1
  • 1
Behrouz Ghazi
  • 399
  • 2
  • 7
  • 23
  • http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005 – lc. Jan 03 '13 at 15:32

2 Answers2

5

You should be able to use the following:

select c.name ClassName,
    STUFF(( SELECT  distinct ', ' + s.name
            FROM    student s
            WHERE   c.id = s.classid
            FOR XML PATH('')
            ), 1, 2, '')  Names
from class c

Result:

ClassName | Names
A         | George
B         | Alex, Anjel, Jenifer
C         | Alex, Joe, Micheal

Here is the working query that I used:

;with class(id, name) as
(
    select 1, 'A'
    union all
    select 2, 'B'
    union all
    select 3, 'C'
),
student(id, name, classid) as
(
    select 1, 'Alex', 3
    union all
    select 2, 'Alex', 3
    union all
    select 3, 'Alex', 3
    union all
    select 4, 'Joe', 3
    union all
    select 5, 'Micheal', 3
    union all
    select 6, 'Jenifer', 2
    union all
    select 7, 'Anjel', 2
    union all
    select 8, 'Alex', 2
    union all
    select 9, 'George', 1
)
select c.name,
    STUFF(( SELECT  distinct ', ' + s.name
            FROM    student s
            WHERE   c.id = s.classid
            FOR XML PATH('')
            ), 1, 2, '') Names
from class c
Taryn
  • 242,637
  • 56
  • 362
  • 405
1

You could try this:

SELECT 
    distinct
    S.Classid,
    (
        SELECT name + ','
        FROM Student S2
        WHERE S2.Classid = S.Classid
        FOR XML PATH('')
    ) StdName,
    C.name ClsName
FROM 
Student S INNER JOIN Class C
ON S.Classid = C.id
Mithrandir
  • 24,869
  • 6
  • 50
  • 66
  • You may want to make it `','+name` and then [`STUFF`](http://msdn.microsoft.com/en-us/library/ms188043.aspx) that to remove the first character, so that it doesn't end with a comma. – Lucero Jan 03 '13 at 15:36