This is called String aggregation or Grouped concatenation.
There are multiple techniques. All are described in Aaron Bertrand's articles, eg Grouped Concatenation in SQL Server.
The fastest and simplest to use is to create and use a SQLCLR Aggregate. Using GROUPED_CONCAT_S as Aaron Bertrand does:
SELECT
SubjectID,
dbo.GROUP_CONCAT_S(StudentfName + ' ' + StudentsName, 1)
FROM dbo.Students
GROUP BY SubjectID
ORDER BY SubjectID;
Writing and deploying the SQLCLR aggregate requires a few steps, but the memory, performance and usability benefits are significant.
SQL Server 2017 will offer a native STRING_AGG
that will be faster even than SQLCLR, eg:
SELECT
SubjectID,
STRING_AGG(StudentfName + ' ' + StudentsName, 1)
FROM dbo.Students
GROUP BY SubjectID
ORDER BY SubjectID;
Next comes XML PATH. It's easier to type but not that easy to use. Essentially, you convert all fields to XML elements and combine them with an XPATH using an empty string as an element tag:
SELECT SubjectID,
Students = STUFF((SELECT N', ' +
StudentfName + ' ' + StudentsName
FROM Students AS p2
WHERE p2.SubjectID = p.SubjectID
ORDER BY StudentfName, StudentsName
FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)')
,1, 2, N'')
FROM Students AS p
GROUP BY subjectid
ORDER BY subjectid;
Notice the PATH, TYPE).value(...)
function. If the fields contained any characters that have special meaning for XML like '
, <
or &
, they would get XML encoded, eg to >
. ,TYPE).value()
returns the element's value instead.
The other techniques aren't really used because they are more cumbersome and far slower.