我正在寻找聚合函数的sql模式来聚合数组。如果我有2行:
select id, *aggregate_function*(array)
from table
group by id
我想做以下事情:
|id | *aggregate_function* |
|-----+-----------------------|
|1 | [1,2,3,4,5,6,7,8] |
|-----------------------------|
我希望结果是:
sublime_plugin.py
没有本地postgres功能可以执行此聚合。但也许有sql模式可以在这里使用?
答案 0 :(得分:4)
这样的事情应该有效:
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
有关于在此处构建自定义函数的一些讨论:Concatenate/merge array values during grouping/aggregation
答案 1 :(得分:1)
您可以取消,然后分组:
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