【问题标题】:How to concatenate all rows in SQL Server 2008 using inner join?如何使用内连接连接 SQL Server 2008 中的所有行?
【发布时间】:2020-06-24 00:30:08
【问题描述】:

这是两张表:

用户

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 sql-server-2008


【解决方案1】:

在 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 Server 的最新版本支持string_agg(),因此这种方法是多余的。

【讨论】:

    猜你喜欢
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2011-07-17
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多