Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to collect multiple values as a single string in postgres?

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 ?

like image 851
Daud Avatar asked Oct 23 '12 07:10

Daud


People also ask

How do I extract a string from a PostgreSQL?

SUBSTRING() function The PostgreSQL substring function is used to extract a string containing a specific number of characters from a particular position of a given string. The main string from where the character to be extracted. Optional. The position of the string from where the extracting will be starting.

What is $$ in Postgres?

A dollar sign ($) followed by digits is used to represent a positional parameter in the body of a function definition or a prepared statement. In other contexts the dollar sign may be part of an identifier or a dollar-quoted string constant.

Is Postgres multi threaded?

The PostgreSQL server is process-based (not threaded). Each database session connects to a single PostgreSQL operating system (OS) process. Multiple sessions are automatically spread across all available CPUs by the OS. The OS also uses CPUs to handle disk I/O and run other non-database tasks.


1 Answers

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

like image 198
John Woo Avatar answered Sep 19 '22 12:09

John Woo