问题
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 |
+---------+-----------+----------+------------------+
回答1:
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
回答2:
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)
来源:https://stackoverflow.com/questions/3098201/correcting-the-sql-syntax