sql >> Database teknologi >  >> RDS >> PostgreSQL

postgres array_agg FEJL:kan ikke akkumulere arrays af forskellig dimensionalitet

Eksempeldata:

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}'   );

Du bør aggregere arrays-elementer, ikke arrays. Brug 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)    

Alternativt kan du oprette et tilpasset aggregat. Du skal bruge en funktion til at flette arrays (sammenkædning med fjernelse af dubletter):

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;


  1. Sessionsændringsudløser?

  2. Kan ikke starte MySQL fra terminalen

  3. Sådan eksporteres forespørgselsresultater til en CSV-fil i SQL Developer (Oracle)

  4. Undslippe MYSQL-kommandolinjer via Bash Scripting