I’ve searched many threads, sites, and blogs, as well as the API and can’t seem to figure this one out. I want to create a CSV string from rows in a junction table, but here’s the catch. It needs to be for an entire set of data. I know, confusing, here’s the breakdown.
Let’s use the generic example with the following tables:
- Students (ID, Name, Gpa)
- Classes (ID, Dept, Level)
- StudentsInClasses (StudentID, ClassID)
Say I want to query for all classes, but within that query (for each record) I want to also get a CSV string of the Student IDs in each of the classes. The results should look something like this:
Class StudentsID_CSVString
----- --------------------
BA302 1,2,3,4,5,6,7,8,9
BA479 4,7,9,12,15
BA483 7,9,12,18
I tried to use a coalesce statement like the following, but I can’t get it to work because of the goofy syntax for coalesce. Is there a better way to accomplish this goal or am I just making a dumb syntactical error?
declare @StudentsID_CSVString varchar(128)
select Dept + Level as 'Class',
coalesce(@StudentsID_CSVString + ',', '')
+ CAST(StudentID as varchar(8)) as 'StudentsID_CSVString'
from Classes
left outer join StudentsInClasses ON Classes.ID = StudentsInClasses.ClassID
I used the following code to test:
declare @Students table (ID int, Name varchar(50), Gpa decimal(3,2))
declare @Classes table (ID int, Dept varchar(4), [Level] varchar(3))
declare @StudentsInClasses table (StudentID int, ClassID int)
declare @StudentsID_CSVString varchar(128)
insert into @Students (ID) values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16),(17),(18)
insert into @Classes (ID, Dept, [Level]) values (1, 'BA', '302'), (2, 'BA', '379'), (3, 'BA', '483')
insert into @StudentsInClasses (StudentID, ClassID) values
(1,1),(2,1),(3,1),(4,1),(5,1),(6,1),(7,1),(8,1),(9,1),
(4,2),(7,2),(9,2),(12,2),(15,2),
(7,3),(9,3),(12,3),(18,3)
With the technique to fill a variable
@StudentsID_CSVStringwith a comma separated string you will only be able to get the string for one class at a time. To get more than one class in the result set you can usefor xml path.Test the query here: https://data.stackexchange.com/stackoverflow/q/115573/