Correcting the SQL syntax?

匆匆过客 提交于 2019-12-13 03:24:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!