postgres array_agg ERROR: cannot accumulate arrays of different dimensionality

前端 未结 1 509
滥情空心
滥情空心 2021-02-07 17:38

I have a parcels table in postgresql in which the zoning and zoning_description columns are array_agg cast over to text. the new.universities table has 9 rows and I need to retu

相关标签:
1条回答
  • 2021-02-07 18:17

    Example data:

    create table my_table(name text, numbers text[], letters text[]);
    insert into my_table values
        ('first',  '{1, 2}', '{a}'   ),
        ('first',  '{2, 3}', '{a, b}'),
        ('second', '{4}',    '{c, d}'),
        ('second', '{5, 6}', '{c}'   );
    

    You should aggregate arrays elements, not arrays. Use unnest():

    select 
        name, 
        array_agg(distinct number) as numbers, 
        array_agg(distinct letter) as letters
    from 
        my_table, 
        unnest(numbers) as number, 
        unnest(letters) as letter
    group by name;
    
      name  | numbers | letters 
    --------+---------+---------
     first  | {1,2,3} | {a,b}
     second | {4,5,6} | {c,d}
    (2 rows)    
    

    Alternatively, you can create a custom aggregate. You need a function to merge arrays (concatenation with duplicates removing):

    create or replace function public.array_merge(arr1 anyarray, arr2 anyarray)
        returns anyarray language sql immutable
    as $$
        select array_agg(distinct elem order by elem)
        from (
            select unnest(arr1) elem 
            union
            select unnest(arr2)
        ) s
    $$;
    
    create aggregate array_merge_agg(anyarray) (
        sfunc = array_merge,
        stype = anyarray
    );
    
    select 
        name, 
        array_merge_agg(numbers) as numbers, 
        array_merge_agg(letters) as letters
    from my_table
    group by name;
    
    0 讨论(0)
提交回复
热议问题