This question already has an answer here:
If there is a table called employee
EmpID EmpName
---------- -------------
1 Mary
1 John
1 Sam
2 Alaina
2 Edward
Result I need in this format:
EmpID EmpName
---------- -------------
1 Mary, John, Sam
2 Alaina, Edward
Q: this record is in same Employee
table. I have almost no experience using UDFs, stored procedures, I need to be done this thing through query.Is this possible without using UDFs, SP's.
An example of #1
How to strip the final comma - is on your own
A CLR aggregate c# code for #2
The chosen answer from @OlegDok's may return the correct result. But the performance can be terrible. This test scenario will illustrate it.
Creation of a temp table:
This is only 10.000 rows. But lots of identical EmpId.
This query in Oleg's answer took 64 seconds on my database.
Distinct is not the correct way of cleaning up rows in this situation. To avoid this cartesian join, reduce the initial number of IDs before joining like this.
This is the correct way of handling this:
This takes less than 1 second
I think there is no
GROUP_CONCAT
function in MSSQL. This article shows different ways of concactenating row values.Concatenating values when the number of items is small and known upfront
More ways on this link.
This is the solution for the example given in the beginning: