将相关 table 中的值转换为逗号分隔列表

Convert values in related table to comma-separated list

我有两个 SQL 服务器表:

TableA                  TableB
+------+--------+       +-----+------------+
| aid  |  Name  |       | aid |   Activity |
+------+--------+       +-----+------------+ 
| 1    |   Jim  |       | 1   |   Skiing   |
| 2    |   Jon  |       | 1   |   Surfing  |
| 3    |   Stu  |       | 1   |   Riding   |
| 4    |   Sam  |       | 3   |   Biking   |
| 5    |   Kat  |       | 3   |   Flying   |
+------+--------+       +-----+------------+

我正在尝试以下结果,其中相关活动位于以逗号分隔的列表中:

+------+--------+------------------------------+
| aid  |  Name  |   Activity                   |
+------+--------+------------------------------+
| 1    |   Jim  |  Skiing, Surfing, Riding     |
| 2    |   Jon  |  NULL                        |
| 3    |   Stu  |  Biking, Flying              |
| 4    |   Sam  |  NULL                        |
| 5    |   Kat  |  NULL                        |
+------+--------+------------------------------+ 

我试过了:

SELECT  aid, Name, STRING_AGG([Activity], ',') AS Activity
FROM    TableA 
        INNER JOIN TableB
        ON TableA.aid = TableB.aid
GROUP BY aid, Name

有人可以帮我解决这个 SQL 查询吗?谢谢。

如果您使用 SQL Server 2017 或更高版本,您可以使用 OUTER APPLY 聚合字符串。

drop table if exists #TableA;
go
create table #TableA (
  aid            int not null,
  [Name]         varchar(10) not null);

insert #TableA(aid, [Name]) values 
(1, 'Jim'),
(2, 'Jon'),
(3, 'Stu'),
(4, 'Sam'),
(5, 'Kat');

drop table if exists #TableB;
go
create table #TableB (
  aid            int not null,
  [Activity]     varchar(10) not null);

insert #TableB(aid, [Activity]) values 
(1, 'Skiing'),
(1, 'Surfing'),
(1, 'Riding'),
(3, 'Biking'),
(3, 'Flying');

select a.aid, a.[Name], oa.sa
from #TableA a
     outer apply (select string_agg(b.Activity, ', ') sa
                  from #TableB b
                  where a.aid=b.aid) oa;
Name    sa
Jim     Skiing, Surfing, Riding
Jon     NULL
Stu     Biking, Flying
Sam     NULL
Kat     NULL