T-Sql查询情况 - 需要一个最大员工数量的departmentID?

时间:2013-03-13 13:32:02

标签: sql-server tsql count max

假设员工表中有员工详细信息和员工的详细信息。 获得每个deptid的员工数量,

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的方法,

感谢

2 个答案:

答案 0 :(得分:0)

  

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

SELECT TOP 1  DepartmentID, 
       COUNT(EmployeeID) 
FROM EmployeeTable
GROUP BY DepartmentID
ORDER BY COUNT(EmployeeID) DESC

答案 1 :(得分: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)