我有两张桌子
Employee(empid integer,mgrid integer,deptid integer,salary 整数)
部门(deptid integer,deptname text),
我正在努力寻找拥有最多员工数量的部门。 我尝试了这个,但我得到了所有部门的ID,如何获得拥有最多员工的部门ID。
(select name from employe_info limit 100) order by name;
答案 0 :(得分:1)
这取决于您的数据库,但逻辑是相同的。您想对结果进行排序,然后抓住结果的顶部。
在sql-server,Access,Teradata和其他一些数据库中你可以使用SELECT TOP 1 dept.DeptName,
COUNT(emp.EmpId) AS NUM_OF_EMPLOYEES
FROM Dept dept
INNER JOIN Employee emp
ON dept.DeptId = emp.deptId
GROUP BY dept.DeptName
ORDER BY NUM_OF_EMPLOYEES DESC
:
SELECT dept.DeptName,
COUNT(emp.EmpId) AS NUM_OF_EMPLOYEES
FROM Dept dept
INNER JOIN Employee emp
ON dept.DeptId = emp.deptId
GROUP BY dept.DeptName
ORDER BY NUM_OF_EMPLOYEES DESC
LIMIT 1
在MySQL或Postgres上你会使用LIMIT:
SELECT dept.DeptName,
COUNT(emp.EmpId) AS NUM_OF_EMPLOYEES
FROM Dept dept
INNER JOIN Employee emp
ON dept.DeptId = emp.deptId
WHERE ROWNUM=1
GROUP BY dept.DeptName
ORDER BY NUM_OF_EMPLOYEES DESC
在Oracle中,您使用RowNum:
Utility().displayAlertMessage(Message.INTERNETISNOTCONNECTED, controller: self)