[英]How to concatenate all rows in SQL Server 2008 using inner join?
下面是两张表:
用户
row_id user_id
1 1
1 2
1 3
2 1
用户名
user_id username
1 foo
2 bar
3 test
如何按 row_id 分组,加入两个表并连接用户名? 例如:
查询应该返回
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()
使得这种方法是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.