在Count聚合函数上使用Min聚合函数

时间:2018-05-18 12:30:23

标签: sql aggregate-functions

我使用了这个查询:

 select D.DeptID, D.Dept, count(E.EmployeeID) as TotalStaff
 from Employees as E
 right join Departments as D
 on D.DeptID = E.DeptID 
 group by D.DeptID, D.Dept;

要归还:

DeptID_|_Dept___________|TotalStaff
40     | Marketing      | 2
50     | Accounting     | 3
60     | Manager        | 3
70     | GeneralStaff   | 1
80     | HumanResources | 1
90     | Production     | 0
100    | Sales          | 0

现在我想列出部门ID,部门和员工人数最少的部门员工,所以我试过这个:

SELECT MIN(mycount) 
FROM 
(
 select D.DeptID, count(E.EmployeeID) as mycount
 from Employees as E
 right join Departments as D
 on D.DeptID = E.DeptID 
 group by D.DeptID
);

但是我收到一条错误,指出:';'附近的语法不正确。 我想做的就是返回员工人数最少的部门。请任何人帮助我。

4 个答案:

答案 0 :(得分:2)

请尝试以下查询:

最小值:

 select min(A.mycount) as min_count
    from  (
         select D.DeptID, count(E.EmployeeID) as mycount
         from Departments as D
         left outer join Employees as E on D.DeptID = E.DeptID 
         group by D.DeptID
    ) as A

有关最大值:

select max(A.mycount) as max_count
from  (
     select D.DeptID, count(E.EmployeeID) as mycount
     from Departments as D
     left outer join Employees as E on D.DeptID = E.DeptID 
     group by D.DeptID
) as A

答案 1 :(得分:1)

您错过了subquery alise

所以,你的子查询就像那样

SELECT MIN(mycount) 
FROM (select D.DeptID, count(E.EmployeeID) as mycount
      from Employees as E
      right join Departments as D on D.DeptID = E.DeptID 
      group by D.DeptID
     ) s; -- alise missed 

答案 2 :(得分:1)

尝试添加

as tablename

在你的最后一次之后)和决赛之前;

答案 3 :(得分:0)

编写此查询的常规方法是使用ANSI标准rank()函数:

select d.*
from (select D.DeptID, D.Dept, count(E.EmployeeID) as TotalStaff,
             rank() over (order by count(E.EmployeeID) asc) as seqnum
      from Departments d left join
           Employees E
           on D.DeptID = E.DeptID 
      group by D.DeptID, D.Dept
     ) d
where seqnum = 1;

请注意,我还将JOIN切换为LEFT JOINLEFT JOIN通常更容易遵循(至少对于从左到右阅读语言的人),因为它表示将所有行保留在第一个表而不是最后一个表中