如何在postgresql中使用折叠列区分一组行?

时间:2017-09-11 22:16:09

标签: postgresql

例如,我有这个表

 id_plant | name | petals
----------+------+--------
 12       | foo  |   3   
 13       | bar  |   3    
 14       | foo  |   6    

我需要使用不同的名称并拥有一个包含所有花瓣值的数组。 对于条目foo

结果:

 name | petals
------+--------
 foo  | [3, 6]

1 个答案:

答案 0 :(得分:1)

使用array_agg().

with my_table(id_plant, name, petals) as (
values
    (12, 'foo', 3),
    (13, 'bar', 3),
    (14, 'foo', 6)
)

select name, array_agg(petals) as petals
from my_table
group by name;

 name | petals 
------+--------
 foo  | {3,6}
 bar  | {3}
(2 rows)