Question

Please help me solve this query. I want to find the count of employees where employee nos. starting with T and N from employee table which is grouped by District. The query is given below

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

The problem is that the result which I am getting is same for the employee no starting with both T and N.

Was it helpful?

Solution

Just add or null to the count expression

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 counts not nulls. As your original expression returns either true or false it would always be counted. false or null evaluates to null so it is not counted.

There is an optimization to the where clause

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

OTHER TIPS

Try this Query:

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top