首页 > 解决方案 > Postgresql - 如何组合这两个查询

问题描述

我尝试将这两个查询合二为一。

这些查询的结果是给定运营商接受/拒绝的申请数量。

我想在三列中得到这样的结果:接受申请的数量、被拒绝的申请数量和分配给它的操作员。

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;

标签: postgresqldata-sciencebusiness-intelligence

解决方案


使用条件聚合:

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;

您可以添加您喜欢的顺序。


推荐阅读