user2889419
user2889419

Reputation:

Postgresql select rows(a result) as array

Assume I have following table, plus some data.

create table "common"."log"("id" bigserial primary key, 
                            "level" int not null default 0);

Now I have this select query that would return something like this.
select * from common.log where id=147;

+------+--------+
|id    |level   |
+------+--------+
|147   |1       |
|147   |2       |
|147   |2       |
|147   |6       |
|147   |90      |
+------+--------+

Now I like to have something like following rather above

+------+---------------+
|id    |arr_level      |
+------+---------------+
|147   |{1,2,2,6,90}   |
+------+---------------+

So is there any implicit select clause/way for doing this? thanks.

pgsql v9.3

Upvotes: 0

Views: 248

Answers (2)

harmic
harmic

Reputation: 30577

Another way, probably more useful if you have more than one id to query:

SELECT id, array_agg(level) FROM common.log GROUP BY id;

See: aggregate functions.

Upvotes: 1

geoandri
geoandri

Reputation: 2428

You can user array function like this

 Select '147' as id,array(select level from common.log where id=147) as arr_level;

Upvotes: 1

Related Questions