postgresql将数组聚合到一个具有所有元素的union的单个数组中

时间:2022-05-07 22:55:30

I'm looking for a sql pattern for an aggregate function to aggregate arrays. If I have 2 rows:

我正在寻找一个聚合函数的sql模式来聚合数组。如果我有2行:

|id  |     array     |
|----+---------------|
|1   |    [1,2,3,4]  |
|1   |    [5,6]      |
|1   |    [7,8]      |
|--------------------|

And I want to do the following:

我想做以下事情:

select id, *aggregate_function*(array) from table group by id

通过id从表组中选择id,* aggregate_function *(数组)

I want the result to be:

我希望结果如下:

|id   | *aggregate_function*  |
|-----+-----------------------|
|1    | [1,2,3,4,5,6,7,8]     |
|-----------------------------|

There is no native postgres function that does this aggregation. But perhaps there's sql pattern that can be used here?

没有本地postgres函数执行此聚合。但也许有sql模式可以在这里使用?

2 个解决方案

#1


2  

Something like this should work:

像这样的东西应该工作:

with mytable as
(
select 1 as id, array[1, 2, 3, 4] as myarray

union all

select 1 as id, array[5, 6] as myarray

union all 

select 1 as id, array[7, 8] as myarray
)

select
  id,
  array_agg(elements order by elements)
from mytable, unnest(myarray) as elements
group by id

There's some discussion about building the custom function here: Concatenate/merge array values during grouping/aggregation

这里有关于构建自定义函数的一些讨论:在分组/聚合期间连接/合并数组值

#2


1  

You can unnest and then group by:

您可以取消,然后分组:

WITH x (id, arr) AS (
  VALUES 
    (1, ARRAY[1,2,3,4])
  , (1, ARRAY[5,6])
  , (1, ARRAY[7, 8])
)
SELECT id, ARRAY_AGG(splitup) 
FROM (
    SELECT 
        id
      , unnest(arr) splitup 
    FROM x) splitup
GROUP BY 1

#1


2  

Something like this should work:

像这样的东西应该工作:

with mytable as
(
select 1 as id, array[1, 2, 3, 4] as myarray

union all

select 1 as id, array[5, 6] as myarray

union all 

select 1 as id, array[7, 8] as myarray
)

select
  id,
  array_agg(elements order by elements)
from mytable, unnest(myarray) as elements
group by id

There's some discussion about building the custom function here: Concatenate/merge array values during grouping/aggregation

这里有关于构建自定义函数的一些讨论:在分组/聚合期间连接/合并数组值

#2


1  

You can unnest and then group by:

您可以取消,然后分组:

WITH x (id, arr) AS (
  VALUES 
    (1, ARRAY[1,2,3,4])
  , (1, ARRAY[5,6])
  , (1, ARRAY[7, 8])
)
SELECT id, ARRAY_AGG(splitup) 
FROM (
    SELECT 
        id
      , unnest(arr) splitup 
    FROM x) splitup
GROUP BY 1