如何使用内部联接连接 SQL Server 2008 中的所有行?

How to concatenate all rows in SQL Server 2008 using inner join?

这是 2 个表格:

用户

row_id  user_id
1       1
1       2
1       3
2       1

用户名

user_id    username
1          foo
2          bar
3          test

如何按 row_id 分组,连接两个表并连接用户名?例如:

查询应该return

row_id     username
1          foo, bar, test
2          foo

在 SQL Server 2008 中,您需要使用 XML hack:

select r.row_id,
       stuff( (select ', ' + un.username
               from users u join
                    usernames un
                    on u.user_id = un.user_id
               where u.row_id = r.row_id
               for xml path ('')
              ), 1, 2, ''
            ) as names
from (select distinct row_id from users) r;

更新版本的 SQL 服务器支持 string_agg() 使此方法变得多余。