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

Hvordan man betinget grupperer i kolonne uden at bruge FULD YDRE JOIN

Dette er en simpel betinget aggregering, så vidt jeg kan se:

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;

Hvis du ønsker et tomt array i stedet for en NULL værdi, skal du pakke aggregeringsfunktionerne ind i en 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;


  1. Hvordan indstiller man tilstand i følgende kode for at markere den aktuelle side i paginering?

  2. Oracle Case Statement forklaret med tips og eksempler

  3. hvordan man indstiller et array som en mysql brugervariabel

  4. Gem UUID v4 i MySQL