2013-07-17 150 views
0

我想要計算所有未結頭寸,「papatable」表包含所有可用頭寸,「employee」表包含所有員工在該位置。當我運行以下聲明我收到SQL左連接不返回「0」或空

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’或‘空’也是可以接受的

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 

回答

3

的問題是,你被包括where子句中的列emp撤消left outer join

您需要的條件移至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是爲emp.emp_statusemp.departmentwhere子句中的有效值。)

+0

這casues每個部門有計數1 –