聚合/连接的 SQL 查询

2022-01-16 00:00:00 sql tsql sql-server sql-server-2008-r2

我有一张这样的桌子:

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

SQL 查询应该是什么来聚合如下结果:

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

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

推荐答案

注意:STUFF 函数只是从返回的字符串中删除前导/.

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

相关文章