我有一个表列出了工作,而另一个表列出了工作的应用程序。我想做一个视图,在其中列出作业表中的所有作业详细信息,并在其中一列显示该作业的应用程序数量。
到目前为止,我已经完成了上述操作。问题在于,没有申请的工作根本不会出现,而应该只显示为0。这可能是因为没有申请人的工作不会在申请表中列出任何job_id。
select count(a.job_id) "no. of applicants",
p.job_id,
p.status,
p.JOB_TYPE,
p.EMPLOYER_ID,
from application a
join job p
on a.job_id=p.job_id
where p.status='OPEN'
group by p.job_id,
p.status,
p.JOB_TYPE,
p.EMPLOYER_ID;
答案 0 :(得分:0)
您需要切换表格-从“作业”中选择并加入“应用程序”,如下所示:
select count(a.job_id) "no. of applicants",
p.job_id,
p.status,
p.JOB_TYPE,
p.EMPLOYER_ID,
from job a
join application p
on a.job_id=p.job_id
where p.status='OPEN'
group by p.job_id,
p.status,
p.JOB_TYPE,
p.EMPLOYER_ID;
另一种解决方案是使用子查询来计算编号。的申请者,但是由于您只想在“申请”表中使用status ='OPEN',因此您仍然必须加入。
答案 1 :(得分:0)
我想那应该是外部加入。我简化了您的表(因为您没有提供测试用例,所以不想输入太多内容)。
SQL> with
2 application (job_id) as
3 (select 1 from dual union all
4 select 2 from dual
5 ),
6 job (job_id, status) as
7 (select 1, 'OPEN' from dual union all
8 select 2, 'CLOSED' from dual union all
9 select 3, 'OPEN' from dual --> no application for this job
10 )
11 select count(a.job_id) no_of_applicants,
12 p.job_id,
13 p.status
14 from job p left join application a on p.job_id = a.job_id --> LEFT (OUTER) JOIN
15 group by p.job_id, p.status;
NO_OF_APPLICANTS JOB_ID STATUS
---------------- ---------- ------
1 2 CLOSED
0 3 OPEN --> job with no applications
1 1 OPEN
SQL>
答案 2 :(得分:0)
这可能会帮助:
select isnull(count(a.job_id),0) "no. of applicants",
p.job_id,
p.status,
p.JOB_TYPE,
p.EMPLOYER_ID,
from application a
right join job p
on a.job_id=p.job_id
where p.status='OPEN'
group by p.job_id,
p.status,
p.JOB_TYPE,
p.EMPLOYER_ID;
答案 3 :(得分:0)
您需要一个left join
,以便保留符合where
条件的所有作业:
select j.job_id, j.status, j.JOB_TYPE, j.EMPLOYER_ID,
count(a.job_id) as num_applicants
from job j left join
application a
on a.job_id = j.job_id
where j.status = 'OPEN'
group by j.job_id, j.status, j.JOB_TYPE, j.EMPLOYER_ID;
也就是说,您可能会发现相关子查询更易于表达逻辑:
select j.*
(select count(*)
from application a
where a.job_id = j.job_id
) as num_applications
from job j
where j.status = 'OPEN'