Hi,
How to modify my select to eliminate the "duplicate"?
My question could be explained better in the sample case.
-- sample data and code
If there is a table called #_Stu
SubjectID StudentName RoleType
1 Mary M
1 John M
1 Sam M
2 Alaina M
2 Edward M
3 Trouble M
3 Maker Null
Result I expected was:
SubjectID StudentName RoleType
1 Mary, John, Sam M
2 Alaina, Edward M
3 Maker, Trouble M
But currently I got
SubjectID StudentName RoleType
1 Mary, John, Sam M
2 Alaina, Edward M
3 Maker, Trouble Null
3 Maker, Trouble M
Select distinct ST2.SubjectID, St2.RoleType,
substring(
(
Select ','+ST1.StudentName AS [text()]
From dbo.#_Stu ST1
Where ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID, ST1.RoleType
For XML PATH ('')
), 2, 1000) [Students]
From dbo.#_Stu ST2
and, by the way, adding another select on top to filter out the Null is not an valid option because there are legit null records, i.e. multiple line of subjectID 4 with Null roleType are concatenated into one line correctly.
if object_ID('tempdb..#_Stu') is not null drop table #_Stu;
Create table #_Stu (SubjectID int, StudentName varchar(20), RoleType Varchar(5))
Insert into #_Stu
Select 1, 'Mary', 'M' union
Select 1, 'John', 'M' union
Select 1, 'Sam', 'M' union
Select 2, 'Alaina', 'M' union
Select 2, 'Edward', 'M' union
Select 3, 'Trouble', 'M' union
Select 3, 'Maker', Null
drop table #_Stu;
Thanks!