简体   繁体   中英

ORACLE SQL: Show the department name, id, and # of employees of the dept. that has the least # of employees

NOTE, this is a homework question!

Show department number, department name, and the number of employees working in the department that has the least number of employees.

I can figure out how many employees each department has, but how do I show just the department with the least number of employees?

SELECT employees.department_id, departments.department_name, COUNT(employee_id)
FROM employees
JOIN departments
ON employees.department_id = departments.department_id
GROUP BY employees.department_id, departments.department_name;

What you need is a having clause, which allows you to apply a condition after the group by clause is applied. In other words, it allows you to apply a condition on an aggregate expression:

SELECT employees.department_id, departments.department_name, COUNT(employee_id)
FROM employees
JOIN departments
ON employees.department_id = departments.department_id
GROUP BY employees.department_id, departments.department_name;
HAVING COUNT(*) > 5 -- Here!

Oracle (and most other DBMSes) support Windowed Aggregate Functions, those are usually much more efficient than old-style SQL:

SELECT department_id, department_name, CNT
FROM
 (
   SELECT employees.department_id, departments.department_name,  
      COUNT(employee_id) AS CNT, 
      RANK() 
      OVER (ORDER BY COUNT(employee_id) DESC) AS rnk
   FROM employees
   JOIN departments
   ON employees.department_id = departments.department_id
   GROUP BY employees.department_id, departments.department_name
 ) dt
WHERE rnk = 1; 

The RANK is processed after aggregation and assigns 1 to the highest COUNT, simply run the inner SQL to see the actual data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM