我正在尝试计算所有未平仓头寸,“paposition”表保存所有可用头寸,“员工”表保存所有处于该头寸的员工。当我运行以下声明时,我收到了
Department Job Code Count(*)
10 2 1
10 1 1
但我期待这个;因为“职务代码”中目前没有员工“3”
Department Job Code Count(*)
10 3 0
10 2 1
10 1 1
如何将工作代码3的计数显示为“0”或“null”也可以接受
select pos.department, pos.job_code, count(*)
from paposition pos
left join employee emp
on (pos.department = emp.department
and pos.job_code = emp.job_code)
where pos.job_code in ('1', '2', '3')
and pos.end_date = '01-Jan-1700'
and (emp.emp_status like 'A%'
or emp.emp_status like 'L%')
and emp.department = '0010'
group by pos.department, pos.job_code
order by pos.department, pos.job_code
答案 0 :(得分:3)
问题是您要通过在left outer join
子句中添加emp
列来撤消where
。
您需要将条件移至on
子句:
select pos.department, pos.job_code, count(*)
from paposition pos left join
employee emp
on (pos.department = emp.department and
pos.job_code = emp.job_code and
(emp.emp_status like 'A%' or emp.emp_status like 'L%') and emp.department = '0010'
where pos.job_code in ('1', '2', '3') and
pos.end_date = '01-Jan-1700' and
group by pos.department, pos.job_code
order by pos.department, pos.job_code;
(或者,您也可以在NULL
和where
的{{1}}子句中检查emp.emp_status
是否为有效值。)