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

Come raggruppare condizionalmente in una colonna senza utilizzare FULL OUTER JOIN

Questa è una semplice aggregazione condizionale per quanto posso dire:

select id, 
       array_agg(amount) filter (where type = 'Customer') as customer_array,
       sum(amount) filter (where type = 'Customer') as customer_sum,
       array_agg(amount) filter (where type = 'Partner') as partner_array,
       sum(amount) filter (where type = 'Partner') as partner_sum
from table_a
group by id;

Se vuoi un array vuoto invece di un NULL valore, racchiude le funzioni di aggregazione in un coalesce() :

select id, 
       coalesce((array_agg(amount) filter (where type = 'Customer')),'{}') as customer_array,
       coalesce((sum(amount) filter (where type = 'Customer')),0) as customer_sum,
       coalesce((array_agg(amount) filter (where type = 'Partner')),'{}') as partner_array,
       coalesce((sum(amount) filter (where type = 'Partner')),0) as partner_sum
from table_a
group by id;