7

I have tables :

Project table

id name
-------
1  A
2  B

Assignment table

id name project_id
-------------------
1  A1   1
2  A2   1
3  A3   2

I wish to write a query that returns each project with the name of the assignments created from it, like :

project_id  assignments
-----------------------
1            A1,A2
2            A3

Is there any way to achieve that ?

1 Answer 1

18

You can join the tables and use array_agg to combine the values separated by a comma

SELECT a.id, array_agg(b.name) assignments
FROM    Project a
        INNER JOIN assignment b
          ON a.id = b.project_ID
GROUP BY a.id

SQLFiddle Demo

or by using STRING_AGG

SELECT a.id, STRING_AGG(b.name, ', ' ORDER BY b.name) assignments
FROM    Project a
        INNER JOIN assignment b
          ON a.id = b.project_ID
GROUP BY a.id

SQLFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

With 9.1 string_agg() might be more approriate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.