Sql 从逗号分隔列表中的联接表中获取多个列值
我有3个表,其中包含如下行: 研究报告表格:Sql 从逗号分隔列表中的联接表中获取多个列值,sql,sql-server,sql-server-2017,Sql,Sql Server,Sql Server 2017,我有3个表,其中包含如下行: 研究报告表格: REPORT_ID TOPIC 141 My Report Topic Title 142 Another Report Topic Title 143 Yet Another Report Topic Title ... REPORT_ID PROGRAM_AREA_ID 141 6 141 11 141 12 ... PROGRAM
REPORT_ID TOPIC
141 My Report Topic Title
142 Another Report Topic Title
143 Yet Another Report Topic Title
...
REPORT_ID PROGRAM_AREA_ID
141 6
141 11
141 12
...
PROGRAM_AREA_ID TITLE
6 Program Area One
11 Program Area Two
12 Program Area Three
...
计划区域报告相关表:
REPORT_ID TOPIC
141 My Report Topic Title
142 Another Report Topic Title
143 Yet Another Report Topic Title
...
REPORT_ID PROGRAM_AREA_ID
141 6
141 11
141 12
...
PROGRAM_AREA_ID TITLE
6 Program Area One
11 Program Area Two
12 Program Area Three
...
程序区域表格:
REPORT_ID TOPIC
141 My Report Topic Title
142 Another Report Topic Title
143 Yet Another Report Topic Title
...
REPORT_ID PROGRAM_AREA_ID
141 6
141 11
141 12
...
PROGRAM_AREA_ID TITLE
6 Program Area One
11 Program Area Two
12 Program Area Three
...
此查询当前正在从下面返回结果:
选择rr.report\u id、rr.topic、pa.title作为程序区域
来自研究报告
内部连接程序\u区域\u报告\u REL parr ON rr.report\u id=parr.report\u id
parr.PROGRAM\u area\u id=pa.PROGRAM\u area\u id上的内部连接程序\u区域pa
其中rr.report_id=141
查询结果:
report_id topic program_areas
141 My Report Topic Title Program Area One
141 My Report Topic Title Program Area Two
141 My Report Topic Title Program Area Three
report_id topic program_areas
141 My Report Topic Title Program Area One, Program Area Two, Program Area Three
我需要一个select查询,其结果格式如下:
首选查询结果:
report_id topic program_areas
141 My Report Topic Title Program Area One
141 My Report Topic Title Program Area Two
141 My Report Topic Title Program Area Three
report_id topic program_areas
141 My Report Topic Title Program Area One, Program Area Two, Program Area Three
如何在当前查询中完成此操作?使用string\u agg()
函数:-
SELECT rr.report_id, rr.topic, string_agg(pa.title,',') as program_areas
FROM RESEARCH_REPORTS rr
INNER JOIN PROGRAM_AREAS_REPORTS_REL parr ON rr.report_id = parr.report_id
INNER JOIN PROGRAM_AREAS pa ON parr.program_area_id = pa.program_area_id
WHERE rr.report_id = 141
group by rr.report_id, rr.topic