Postgresql选择行(结果)作为数组

时间:2014-10-31 09:46:02

标签: postgresql

假设我有下表,加上一些数据。

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

现在我有这个选择查询会返回这样的东西 select * from common.log where id=147;

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

现在我喜欢有类似于上面的内容

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

那么有没有隐含的select子句/方法呢?谢谢。

pgsql v9.3

2 个答案:

答案 0 :(得分:1)

你可以像这样用户数组函数

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

答案 1 :(得分:1)

另一种方法,如果您有多个要查询的ID,可能会更有用:

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

请参阅:aggregate functions