我的表有一个integer []类型的列。我希望按col1
分组,求和col2
,然后合并col3
中的数组。
my_table
+-------------------------+
| col1 | col2 | col3 |
| ---- | ---- | --------- |
| qwer | 5 | {1,2,3,4} |
| asdf | 10 | {5,6,7,8} |
| qwer | 2 | {4,9,10} |
+-------------------------+
SELECT col1, SUM(col2) AS sum, ???(col3) AS merge
FROM my_table
GROUP BY col1
This output would be acceptable:
=>
+--------------------------------+
| col1 | sum | merge |
| ---- | --- | ----------------- |
| qwer | 7 | {1,2,3,4,4,9,10} |
| asdf | 10 | {5,6,7,8} |
+--------------------------------+
The output would be ideal (the elements in the integer array are unique):
=>
+------------------------------+
| col1 | sum | merge |
| ---- | --- | --------------- |
| qwer | 7 | {1,2,3,4,9,10} |
| asdf | 10 | {5,6,7,8} |
+------------------------------+
对于???我已经尝试使用array_agg以及使用string_agg将数组转换为字符串,然后转换回数组。我无法让任何这些解决方案起作用。我错过了一个简单的解决方案或功能吗?
答案 0 :(得分:1)
PostgreSQL array_agg函数不接受数组参数。 这是你的解决方案:
SQL命令:
SELECT
xxx.col1,sum(xxx.col2),array_agg(xxx.one_col)
FROM (select col1,col2,unnest(col3) as one_col from tmp2) AS xxx
GROUP BY xxx.col1;