0

find out the 2nd most no. of employee working with dname from emp and dept table.

select d.dname,count(*) "totemp" from emp e,dept d
where e.deptno=d.deptno
group by (d.dname)
having count(*)=(select max(count(*)) from emp e,dept d 
where e.deptno=d.deptno
group by d.dname);

This query will show highest no. of employee working with dname. But i want 2nd highest with dname.

1 Answers1

0

First use grouping to count employees for each dept, then use dense_rank() window function to assign rank values for dept groups and lastly select the dept which is ranked second.

select dname
from (
  select dname, dense_rank() over (order by cnt desc) as rnk
  from (
    select d.dname, count(*) as cnt
    from emp e
    join dept d using (deptno)
    group by d.dname
  ) t
) x
where rnk = 2

Using dense_rank() function you resolve ties properly, so if there are more than one depts with the same number of employees they will all pop up.

You can change your solution using row_number() function to pick any arbitrary dept even if there are ties on second position.

Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72