views:

102

answers:

2

Hi,

Thanks very much for those responded. Is there a way in SQL server that takes the data from table1 and outputs the data like table2?

Thanks!

Table1:

+---------+-----------+----------+------------------+
|  Name   |    DOB    | Agent ID |    Agent Name    |
+---------+-----------+----------+------------------+
| subject | 4/20/1960 | 4444     | Smith            |  
+---------+-----------+----------+------------------+
| subject | 4/20/1960 | 4444     | John             |
+---------+-----------+----------+------------------+
| subject | 4/20/1960 | 4444     | Larry            |
+---------+-----------+----------+------------------+

Table2:

+---------+-----------+----------+------------------+
|  Name   |    DOB    | Agent ID |    Agent Name    |
+---------+-----------+----------+------------------+
| subject | 4/20/1960 | 4444     | Smith,John,Larry |
+---------+-----------+----------+------------------+
+2  A: 

For SQL Server 2005+, use the STUFF & FOR XML PATH to create a comma separated list:

SELECT DISTINCT
       t.name,
       t.dob,
       t.agentid,
       STUFF(ISNULL(SELECT ', ' + x.agentname
                      FROM TABLE1 x
                     WHERE x.agentid = t.agentid
                  GROUP BY x.agentname
                   FOR XML PATH ('')), ''), 1, 2, '')
  FROM TABLE1 t
OMG Ponies
+1  A: 
SELECT DISTINCT t.Name, t.DOB, t.AgentID, x.AgentName 
FROM Table1 t
CROSS APPLY (SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY AgentName) = 1 
                         THEN '' ELSE ', ' END + AgentName 
             FROM Table1
             WHERE AgentID = t.AgentID
             AND AgentName IS NOT NULL
             FOR XML PATH(''))x(AgentName)
Scot Hauder