We help IT Professionals succeed at work.

Concatenate text from multiple rows into a single text string in SQL server

Errol Farro
Errol Farro asked
on
56 Views
Last Modified: 2018-12-12
I need an SQL to produce the result as shown in EXPECTED RESULT

There are three table which must be combined to produce the result as "EXPECTED RESULT". I have been trying several SQL statements with COALESCE, XML PATH, etc... but to no avail.

Any help is greatly appreciated

Course table
============
ID1                  Name1
21                  Math
22                  Chemistry
23                  Physics
24                  History



Student table
=============
Student ID2            Name2
1                        Joe
2                        Mary
3                        Peter      


Attendance table
================
ID1            ID2
21            2
21            3
22            1
22            2      
22            3
23            3
24            2
24            3

Expected result
==============
21            Mary, Peter
22            Joe, Mary, Peter
23            Peter
24            Mary
24            Peter
Comment
Watch Question

Senior .Net Consultant
CERTIFIED EXPERT
Top Expert 2016
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Éric MoreauSenior .Net Consultant
CERTIFIED EXPERT
Top Expert 2016

Commented:
In your expected results, why do you have 2 rows with ID 24?
D BDatabase Developer

Commented:
Try this:
SELECT DISTINCT Course.ID1, STUFF((SELECT ',' + Name FROM Student s INNER JOIN Attendence a ON s.ID2 = a.ID2 WHERE a.ID1 = c.ID1 FOR XML PATH('')), 1, 1, '')
FROM Course c

Open in new window

D BDatabase Developer

Commented:
Slight change:
SELECT	DISTINCT c.ID1, 
		STUFF((SELECT ',' + Name2 FROM Student s INNER JOIN Attendance a ON s.ID2 = a.ID2 WHERE a.ID1 = c.ID1 FOR XML PATH('')), 1, 1, '')
FROM Course c

Open in new window

Author

Commented:
Thank you gents

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions