2017-09-11 29 views
0

例如,我有這個表如何區分postgresql中摺疊列的一組行?

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

我需要不同的名稱,並與所有的花瓣值的數組。 所以對於入門foo

結果:

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

回答

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) 
+0

你還學到新的東西? – user544262772

+0

學習永遠不會遲到。 – klin