I want to present multiple rows data for a particular Id in comma separated list. If it has only one join I have no problem to display but when it includes many tables it is not presented properly.
My data is as follows.
Declare @EmpClass Table(ClassId varchar(10),EmpId int)
INSERT INTO @EmpClass
Values('A',1)
,('B',2)
,('C',3)
Declare @Employees Table (EmpId int, EmpName Varchar(100))
INSERT INTO @Employees
VALUES(1,'RAM')
,(2,'RAJ')
,(3,'LAXMAN')
Declare @EmpSubjects Table (EmpId int, SubjectId int)
INSERT INTO @EmpSubjects
VALUES(1,1)
,(1,2)
,(1,3)
,(2,1)
,(3,1)
,(3,2)
Declare @Subjects Table (SubjectId int, Subject Varchar(100))
INSERT INTO @Subjects
VALUES(1,'Maths')
,(2,'Science')
,(3,'Physics')
,(4,'Physics')
,(5,'Maths')
,(6,'Physics')
I have tried the below code and got the below result
SELECT EC.ClassId,E.EmpId
,ES.SubjectId,Subject
FROM @EmpClass EC
LEFT JOIN @Employees E ON EC.EmpId=E.EmpId
LEFT JOIN @EmpSubjects ES ON E.EmpId=ES.EmpId
LEFT JOIN @Subjects S ON S.SubjectId=ES.SubjectId
WHERE E.EmpId=1
I got the below result
ClassId EmpId SubjectId Subject
A 1 1 Maths
A 1 2 Science
A 1 3 Physics
The result needed as follows.
ClassId EmpId SubjectId Subject
A 1 1 {"1":"Maths","2":"Science","3":"Physics"}
I appreciate your help for this.
Thanks