0

假设员工表有员工详细信息和员工的部门 ID。获取每个部门的员工人数,

select deptId, COUNT(*) from employee group by deptId; 

问题是:要获得具有上述结果集的最大员工数的 deptId,

select Top 1 deptId, COUNT(*) from employee group by deptId order by 2 desc

(2-ref 到查询列表中的第二列)- 可以.. 但是

有没有办法避免订购这套?或编写此 sql 的更好方法,

谢谢

4

2 回答 2

0

没有任何命令,这很难,但尝试

   Select deptId, cnt
   From (Select deptId, count(*) cnt
         from employee
         Group By deptId) Z
   Where cnt = (Select Max(cnt) 
                From (Select deptId, count(*) cnt
                      From employee
                      Group By deptId) ZZ) 
于 2013-03-13T13:46:26.717 回答
0

如果您只想要MAX一个部门内的员工人数,您可以这样做:

SELECT TOP 1  DepartmentID, 
       COUNT(EmployeeID) 
FROM EmployeeTable
GROUP BY DepartmentID
ORDER BY COUNT(EmployeeID) DESC
于 2013-03-13T13:40:03.647 回答