PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Como agrupar condicionalmente na coluna sem usar FULL OUTER JOIN


Esta é uma agregação condicional simples, tanto quanto posso dizer:
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 você quiser um array vazio em vez de um NULL valor, envolva as funções de agregação em um 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;