SQL Query for aggregation/concatenation

谁说胖子不能爱 提交于 2019-12-20 03:48:26

问题


I have a table like this:

ID    Name
----------
1   john
1   molly
2   greg
2   sean
1   holly
2   mill

What should the SQL Query be to aggregate results like the following:

ID  Name
-------------
1   john/molly/holly
2   greg/sean/mill

回答1:


Note: The STUFF function simply removes the leading / from the string returned.

SELECT t1.id, 
       STUFF((SELECT '/' + t2.name
                FROM YourTable t2
                WHERE t1.id = t2.id
                ORDER BY t2.name
                FOR XML PATH('')),1,1,'') AS Name
    FROM YourTable t1
    GROUP BY t1.id


来源:https://stackoverflow.com/questions/7896239/sql-query-for-aggregation-concatenation

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