如何使用内部联接连接SQL Server 2008中的所有行?
以下是两个表格: 用户如何使用内部联接连接SQL Server 2008中的所有行?,sql,sql-server-2008,Sql,Sql Server 2008,以下是两个表格: 用户 row_id user_id 1 1 1 2 1 3 2 1 user_id username 1 foo 2 bar 3 test 用户名 row_id user_id 1 1 1 2 1 3 2 1 user_id username 1 foo 2 bar 3
row_id user_id
1 1
1 2
1 3
2 1
user_id username
1 foo
2 bar
3 test
用户名
row_id user_id
1 1
1 2
1 3
2 1
user_id username
1 foo
2 bar
3 test
如何按行id分组、连接两个表以及连接用户名?例如:
查询应返回
row_id username
1 foo, bar, test
2 foo
在SQL Server 2008中,您需要使用XML攻击:
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 Server的最新版本支持
string\u agg()
使此方法成为多余的方法。请注意:SQL Server 2008和2008 R2目前已失去扩展支持--该升级了!