I have a joint table from 3 different tables like this.
Select DoctorTable.Doctor, NurseTable.Nurse , PatientTable.Patents
FROM PatientTable
LEFT JOIN DoctorTable on DoctorTable.DoctorCode = PatientTable.DoctorCode
LEFT JOIN NurseTable on DoctorTable.DoctorCode = NurseTable.DoctorCode
Patient Doctor Nurse
John Peter Mary
John Peter Amy
Kate Terry Mary
Kate Leo Ivy
Paul NULL NULL
Emily NULL NULL
And I want to join the rows which has the same value with a comma in 'Doctor' Column to have the result below
Patient Doctor Nurse
John Peter Mary, Amy
Kate Terry, Leo Mary, Ivy
Paul Null Null
Emily NULL NULL
As I still have some columns to join with this table and also need to group the rows with ',', using FOR XML PATH('') to group each column will be very slow. So how can I group this table efficiently?
I think the answer is using an aggregation function which concatenates rows in the group. Too bad TSQL does not have one (how hard is that?), but if you don't mind using SQLCLR, here is how to create a user defined aggregate concatenation function with .NET in MSDN:
MSDN String Utility Functions Sample
Then, you can do something like: