SQLPlus如何打印COUNT(*)的MAX?

时间:2014-10-08 16:15:04

标签: sql oracle

我需要帮助打印员工人数最多的部门。既然MAX(COUNT(*))实际上没有用,那么有人可以帮助我吗?

假设我有两个名为dept和emp的表,每个表分别有deptno和empdeptno。 我有这个来计算每个部门的每个员工:

SELECT dept.deptname "Department",
    (SELECT COUNT(*)
     FROM emp
     WHERE emp.empdeptno = dept.deptno) "Number of Employees"
FROM dept
ORDER BY COUNT(*) DESC;

如何在不使用LIMIT和ORDER BY的情况下打印员工人数最多的部门?

1 个答案:

答案 0 :(得分:1)

SELECT dept.deptname "Department", COUNT(emp.empdeptno) AS "Number of Employees"
FROM dept
LEFT JOIN emp ON dept.deptno = emp.empdeptno
GROUP BY dept.deptname
ORDER BY COUNT(emp.empdeptno) DESC

如果dept.deptname不是关键字并且可能会重复,您可以考虑GROUP BY dept.UniqueDepartmentKey, dept.deptname

您可能需要引用别名:GROUP BY "Department",具体取决于您的SQL风格。