Search code examples
postgresqldata-sciencebusiness-intelligence

Postgresql - how to combine these two queries


I try to combine these two queries in one.

the result of these queries is the number of accepted / rejected applications for a given operator.

I want to get such a result - in three column: number of accepted applications , number of rejected applications and operators assigned to it.

select count(applications.id) as number_of_applications, operator_id
from applications
inner join travel p on applications.id = p.application_id
inner join trip_details sp on p.id = sp.trip_id
where application_status ilike '%rejected%'
group by  operator_id
order by number_of_applications desc;


select count(applications.id) as number_of_applications, operator_id
from applications
inner join travel p on applications.id = p.application_id
inner join trip_details sp on p.id = sp.trip_id
where application_status ilike '%accepted%'
group by  operator_id
order by number_of_applications desc;

Solution

  • With conditional aggregation:

    select
      sum(case when application_status ilike '%accepted%' then 1 else 0 end) as number_of_applications_accepted,
      sum(case when application_status ilike '%rejected%' then 1 else 0 end) as number_of_applications_rejected, 
      operator_id
    from applications
    inner join travel p on applications.id = p.application_id
    inner join trip_details sp on p.id = sp.trip_id
    where (application_status ilike '%rejected%') or (application_status ilike '%accepted%')
    group by operator_id;
    

    You can add the ordering that you prefer.