0

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 |
+---------+-----------+----------+------------------+
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
New SQL
  • 1
  • 1
  • First off, you didnt tell us the error and second - that is not valid T-SQL – keithwarren7 Jun 23 '10 at 00:47
  • You need to describe what the error is before anyone can help. – Benny Jun 23 '10 at 00:48
  • The function is PLSQL, as in coded for Oracle or PostgreSQL - not TSQL for SQL Server. If this is to be for SQL Server, what version? Hopefully 2005+? – OMG Ponies Jun 23 '10 at 00:52
  • possible duplicate of [SQL Server: Can I Comma Delimit Multiple Rows Into One Column?](http://stackoverflow.com/questions/2046037/sql-server-can-i-comma-delimit-multiple-rows-into-one-column) – OMG Ponies Jun 23 '10 at 00:55
  • `Table2` violates 1NF because column `Agent Name` uses a non-scalar data type. Better done elsewhere e.g. in a reporting tool. – onedaywhen Jun 25 '10 at 14:54

2 Answers2

2

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
  • 325,700
  • 82
  • 523
  • 502
1
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
  • 246
  • 1
  • 4