Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql aggregate array

I have a two tables

Student -------- Id  Name 1   John     2   David 3   Will  Grade --------- Student_id  Mark 1           A 2           B 2           B+ 3           C 3           A 

Is it possible to make native Postgresql SELECT to get results like below:

Name    Array of marks ----------------------- 'John',     {'A'} 'David',    {'B','B+'} 'Will',     {'C','A'} 

But not like below

Name    Mark ---------------- 'John',     'A' 'David',    'B' 'David',    'B+' 'Will',     'C' 'Will',     'A' 
like image 962
Eazy Avatar asked Jun 07 '12 08:06

Eazy


People also ask

What is aggregate array?

3 Array Aggregates. In an array_aggregate, a value is specified for each component of an array, either positionally or by its index. For a positional_array_aggregate, the components are given in increasing-index order, with a final others, if any, representing any remaining components.

How do I create aggregate function in PostgreSQL?

To define a new aggregate function, one selects a data type for the state value, an initial value for the state, and a state transition function. The state transition function takes the previous state value and the aggregate's input value(s) for the current row, and returns a new state value.

Is coalesce an aggregate function?

The coalesce function can be used to substitute zero or an empty array for null when necessary. Here ANY can be considered either as introducing a subquery, or as being an aggregate function, if the subquery returns one row with a Boolean value.

Can you insert array in PostgreSQL?

There are two accepted syntaxes to insert into array in PostgreSQL – one using ARRAY keyword, and other using quotes & curly braces.


1 Answers

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

SELECT s.name,  array_agg(g.Mark) as marks         FROM student s LEFT JOIN Grade g ON g.Student_id = s.Id GROUP 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'); 
like image 154
Michael Buen Avatar answered Sep 22 '22 03:09

Michael Buen