0

I am using oracle's SQL Developer. To begin with, I have this table:

Name           Null     Type         
-------------- -------- ------------ 
EMPLOYEE_ID    NOT NULL NUMBER(6)    
FIRST_NAME              VARCHAR2(20) 
LAST_NAME      NOT NULL VARCHAR2(25)  
DEPARTMENT_ID           NUMBER(4)    

I would like to retrieve(select) the ID of the department in which are the most employees. I managed through a statement to retrieve all the numbers of the employees in every department:

select count(employee_id), department_id
from employees
group by department_id;

It gives me something like:

count(employee_id)   |     department_id
---------------------|------------------
      6                       100
     16                        30
      1                        12

What I would like to do is ONLY to retrieve the department_id 30, which (in this case) has the most employees.

1 Answer 1

1

A typical way to do this in Oracle:

select department_id
from (select count(employee_id), department_id
      from employees
      group by department_id
      order by count(employee_id) desc
     ) t
where rownum = 1;

If you have potential duplicates and want all the department ids, then a join to the max or analytic function is a better approach. For example:

select department_id
from (select count(employee_id), department_id,
             rank() over (order by count(employee_id) desc) as seqnum
      from employees
      group by department_id
     ) t
where seqnum = 1;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. The first snippet works perfectly but the second one gives me more than one result.
@Theo. . . . The desc will fix that problem (I actually fixed it before I read your comment).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.