I got two tables with data as listed below:
Table1: Student
Table2: Subject
I need the output as:
I got this acheived with below query using for XML PATH
Code:
WITH cte
AS ( SELECT Stu.Student_Id ,
Stu.Student_Name ,
( SELECT Sub.[Subject] + ','
FROM [Subject] AS Sub
WHERE Sub.Student_Id = Stu.Student_Id
ORDER BY Sub.[Subject]
FOR
XML PATH('')
) AS [Subjects]
FROM dbo.Student AS Stu
)
SELECT Student_id [Student Id] ,
student_name [Student Name] ,
SUBSTRING(Subjects, 1, ( LEN(Subjects) - 1 )) AS [Student Subjects]
FROM cte
My question is there a better way to do this without using XML Path?
This is a very good approach and has become pretty well accepted. There are several approaches and this blog post describes a lot of them.
One interesting approach that exists is using the CLR to do the work for you which will significantly reduce the complexity of the query with the trade-off of running external code. Here is a sample of what the class might look like in the assembly.
And that would net a query a bit more like this.
Which is quite a bit simpler obviously. Take it for what it's worth :)
Good day!