sql—从逗号分隔列表中的联接表中获取多个列值

ljsrvy3e  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(381)

我有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_AREA_ID    TITLE
6                  Program Area One
11                 Program Area Two
12                 Program Area Three
...

此查询当前正在从下面返回结果:

SELECT rr.report_id, rr.topic, 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

查询结果:

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

我需要一个select查询,其结果格式如下:
首选查询结果:

report_id    topic                    program_areas
141          My Report Topic Title    Program Area One, Program Area Two, Program Area Three

如何在当前查询中完成此操作?

yqlxgs2m

yqlxgs2m1#

使用 string_agg() function:-

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

相关问题