Try this. I have tested it and it is working.
SELECT t.Time, LEFT(Names , LEN(Names )-1) as Names
FROM yourtable t
CROSS APPLY
(
SELECT t1.Name + ','
FROM yourtable t1
WHERE t.Time= t1.Time
FOR XML PATH('')
) pre_trimmed (Names)
GROUP BY Time, Names;
As you can see, the join of strings from NAME
column is done using CROSS APPLY
. The http://technet.microsoft.com defines 'APPLY' as
The APPLY operator allows you to invoke a table-valued function for each row returned by an outer table expression of a query. The table-valued function acts as the right input and the outer table expression acts as the left input. The right input is evaluated for each row from the left input and the rows produced are combined for the final output. The list of columns produced by the APPLY operator is the set of columns in the left input followed by the list of columns returned by the right input.
While 'CROSS APPLY' as,
CROSS APPLY returns only rows from the outer table that produce a result set from the table-valued function.
The LEFT(Names , LEN(Names )-1)
just trims the resulting string by one character, i.e. removes the extra comma at the end.