2014-05-19 18 views
1

我在多行上执行一系列聚合。我按照一个共同的列进行分组,但我有一些小的字段,我想将所有唯一值合并到一个列中。如何将多个唯一行值合并到多个列中的单个列中?

下面的示例没有聚合计算来简化问题。

例如:

Table A 
    table_a_id integer, 
    column_1 integer, 
    column_2 text, 
    column_3 integer 

SELECT table_a_id, column1, column_2, column_3 
FROM table_a; 

息率

101 | 1 | 'sample value 1' | 20 
101 | 2 | 'sample value 2' | 25 
101 | 3 | 'sample value 3' | 27 

我想:

101 | 1, 2, 3 | 'sample value 1, sample value 2, sample value 3' | 20, 25, 27 

如何做到这一点的PostgreSQL的?

回答

2
select 
  table_a_id, 
  array_to_string(array_agg(distinct column_1), ',') AS the_ones, 
  array_to_string(array_agg(distinct column_2), ',') AS the_twos, 
  array_to_string(array_agg(distinct column_3), ',') AS the_threes 
from table_a 
group by table_a_id 
; 
+1

对于Postgres 9.0,[有一个'string_agg'功能](http://www.postgresql.org/docs/current/interactive/functions-aggregate.html)所以'array_to_string(ARRAY_AGG(FOO ,','))'可以简化为'string_agg(foo,',')'。 – IMSoP

+0

@IMSoP优秀!谢谢! –

相关问题