PostgreSQL-如何结合这两个查询

时间:2019-05-22 21:26:55

标签: postgresql data-science business-intelligence

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

这些查询的结果是给定操作员被接受/拒绝的申请数。

我想得到这样的结果-在三栏中:接受的申请数,拒绝的申请数和分配给它的运算符。

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;

1 个答案:

答案 0 :(得分:2)

有条件聚合:

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;

您可以添加所需的顺序。