Postgresql aggregate array Postgresql aggregate array arrays arrays

Postgresql aggregate array


Use array_agg: http://www.sqlfiddle.com/#!1/5099e/1

SELECT s.name,  array_agg(g.Mark) as marks        FROM student sLEFT JOIN Grade g ON g.Student_id = s.IdGROUP BY s.Id

By the way, if you are using Postgres 9.1, you don't need to repeat the columns on SELECT to GROUP BY, e.g. you don't need to repeat the student name on GROUP BY. You can merely GROUP BY on primary key. If you remove the primary key on student, you need to repeat the student name on GROUP BY.

CREATE TABLE grade    (Student_id int, Mark varchar(2));INSERT INTO grade    (Student_id, Mark)VALUES    (1, 'A'),    (2, 'B'),    (2, 'B+'),    (3, 'C'),    (3, 'A');CREATE TABLE student    (Id int primary key, Name varchar(5));INSERT INTO student    (Id, Name)VALUES    (1, 'John'),    (2, 'David'),    (3, 'Will');


What I understand you can do something like this:

SELECT p.p_name,     STRING_AGG(Grade.Mark, ',' ORDER BY Grade.Mark) As marksFROM StudentLEFT JOIN Grade ON Grade.Student_id = Student.IdGROUP BY Student.Name;

EDIT

I am not sure. But maybe something like this then:

SELECT p.p_name,     array_to_string(ARRAY_AGG(Grade.Mark),';') As marksFROM StudentLEFT JOIN Grade ON Grade.Student_id = Student.IdGROUP BY Student.Name;

Reference here


You could use the following:

SELECT Student.Name as Name,       (SELECT array(SELECT Mark FROM Grade WHERE Grade.Student_id = Student.Id))       AS ArrayOfMarks FROM Student

As described here: http://www.mkyong.com/database/convert-subquery-result-to-array/