Mar*_*and 5 sql subquery 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;
Run Code Online (Sandbox Code Playgroud)
要返回这个:
DeptID_|_Dept___________|TotalStaff
40 | Marketing | 2
50 | Accounting | 3
60 | Manager | 3
70 | GeneralStaff | 1
80 | HumanResources | 1
90 | Production | 0
100 | Sales | 0
Run Code Online (Sandbox Code Playgroud)
现在我想列出员工人数最少的部门的部门 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
);
Run Code Online (Sandbox Code Playgroud)
但我收到一条错误消息:“;”附近的语法不正确。我只想返回员工数量最少的部门。请任何人帮我解决这个问题。
编写此查询的正常方法是使用 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;
Run Code Online (Sandbox Code Playgroud)
请注意,我还将 切换JOIN为LEFT JOIN. LEFT JOIN通常更容易遵循(至少对于从左到右阅读语言的人来说),因为它说将所有行保留在第一个表而不是最后一个表中。