Question

I have a SQL Server 2005 table that records each step of a process as shown below

Time   Name

08.40  Sarah
09.00  Nafira
09.00  Sarah
09.00  Denur
10.00  MuLyono
10.00  Lucky
08.30  MaLa
08.35  Mara

What I would like to do is display a result that has a single line for each ResourceID that shows the time for each event.

Time   Name

08.30  MaLa
08.35  Mara
08.40  Sarah
09.00  Nafira, Sarah, Denur
10.00  MuLyono, Lucky

Any suggestions on how to accomplish this? Thanks for reading and answer ^_^

Was it helpful?

Solution

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.

OTHER TIPS

I modified your sql code into like this and this is work like i want.

select c1.Time,
stuff((select distinct ', '+cast(Nama as varchar(200))
from tbclientdata c2 where c2.time=c1.time
for xml path('')),1,1,'')
from tbclientdata c1
group by c1.Time

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top