PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

So gruppieren Sie bedingt in Spalten, ohne FULL OUTER JOIN zu verwenden

Soweit ich das beurteilen kann, ist dies eine einfache bedingte Aggregation:

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;

Wenn Sie ein leeres Array anstelle von NULL wollen -Wert, packen Sie die Aggregationsfunktionen in ein 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;