Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用内部联接连接SQL Server 2008中的所有行?_Sql_Sql Server 2008 - Fatal编程技术网

如何使用内部联接连接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目前已失去扩展支持--该升级了!