2014-03-03 39 views
0

請幫我解決這個問題。我想找到僱員數量的員工數量。從區域分組的員工表中以T和N開始。下面以T和N開頭的員工數

select 
    m.institution_dist, 
    count(e.emp_pf_acc_number like 'T%') as tcnt, 
    count(e.emp_pf_acc_number like 'N%') as ncnt 
from 
    pf_emp e 
    left join 
    pfmast_institution m on e.emp_workplace_code = m.institution_code 
where 
    e.retired <> 'Y' 
    and emp_classification_code = '3' 
    and m.institution_dist in (
     select dist_name 
     from pfmast_dist 
    ) 
group by m.institution_dist 

問題查詢,給出的是,這我得到的結果是一樣的沒有開始,T和N.

+3

,什麼是錯此查詢?也許如果你給我們一些樣本數據和預期結果,我們可能會提供幫助。 –

+0

爲什麼不嘗試查詢m.institution_dist ='dist1'而不是「m.institution_dist (從pfmast_dist選擇dist_name)」 – ray

回答

2

員工只需添加or null以計數表達

count(e.emp_pf_acc_number like 'T%' or null) as tcnt, 
count(e.emp_pf_acc_number like 'N%' or null) as ncnt 

count計數不爲零。由於您的原始表達式會返回truefalse,因此總是會被計數。 false or null評估爲null因此不計算在內。

有一個優化的where條款

and exists (
    select 1 
    from pfmast_dist 
    where m.institution_dist = dist_name 
) 
1

嘗試此查詢:

Select * from 

(select m.institution_dist, 
     Count(e.emp_pf_acc_number like 'T%') as tcnt 
from pf_emp e 
left join 
pfmast_institution m  on e.emp_workplace_code = m.institution_code 
where e.retired <> 'Y'  
and emp_classification_code = '3' 
and m.institution_dist in (select dist_name from pfmast_dist) 
group by m.institution_dist) x 

full outer join 

(select b.institution_dist,count(a.emp_pf_acc_number like 'N%') as ncnt 
from pf_emp a 
left join 
pfmast_institution b on a.emp_workplace_code = b.institution_code 
where b.retired <> 'Y' 
and emp_classification_code = '3' 
and b.institution_dist in (select dist_name from pfmast_dist) 
group by b.institution_dist) y 
on x.institution_dist = y.institution_dist 
相關問題