I have a postgres query I’m trying to aggregate an array of arrays with different dimensions, a simplified form of the query can be written as:
SELECT n, ARRAY(SELECT UNNEST(a) FROM (SELECT ARRAY_AGG(a) AS a) a) AS a, SUM(q) AS q
FROM (
SELECT 'foo' AS n, '{1,2}'::integer[] AS a, 1 AS q
UNION ALL
SELECT 'foo' AS n, '{3,4,5}'::integer[] AS a, 1 AS q
) results
GROUP BY n
This results in an error:
Query 1 ERROR at Line 1: : ERROR: cannot accumulate arrays of different dimensionality
The result i’m hoping for is:
n | a | q |
---|---|---|
‘foo’ | {1,2,3,4,5} | 2 |
However if the arrays have the same dimensions it works fine, eg:
SELECT n, ARRAY(SELECT UNNEST(a) FROM (SELECT ARRAY_AGG(a) AS a) a) AS a, SUM(q) AS q
FROM (
SELECT 'foo' AS n, '{1,2,3}'::integer[] AS a, 1 AS q
UNION ALL
SELECT 'foo' AS n, '{4,5,6}'::integer[] AS a, 1 AS q
) results
GROUP BY n
Output:
n | a | q |
---|---|---|
‘foo’ | {1,2,3,4,5,6} | 2 |
I have tried asking every LLM on the internet and none can answer it, so it’s down to you humans now, please help.
2
Answers
I answered my own question using built-in JSON functions.
Create once per database:
Then: