Search code examples
sqlsql-serversql-server-2017

Get multiple column values from joined table in a comma separated list


I have 3 tables which contains rows like below:

RESEARCH_REPORTS table:

REPORT_ID   TOPIC
141         My Report Topic Title
142         Another Report Topic Title
143         Yet Another Report Topic Title
...

PROGRAM_AREAS_REPORTS_REL table:

REPORT_ID    PROGRAM_AREA_ID
141          6
141          11
141          12
...

PROGRAM_AREAS table:

PROGRAM_AREA_ID    TITLE
6                  Program Area One
11                 Program Area Two
12                 Program Area Three
...

This query is currently returning me the results from down below:

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

Query Results:

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

I need a select query which results in the following format:

Preferred Query Results:

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

How can I accomplish this on my current query?


Solution

  • Use 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