我有两个表:
Employee(EmployeeNum, Ename, Job, MGR, HireDate, SAL,COMM, DeptNo)
Department (DeptNo, DName, LOC)
我正在尝试查找以下内容:
问:每个部门中最近雇用的员工是谁?查询是:
SELECT Employee.Ename,
(SELECT MAX(HireDate)
FROM Department
WHERE Employee.DeptNo = Department.DeptNo)
AS HireDate
FROM Employee;
但是我遇到以下错误:
消息8120,第16层,状态1,第112行 选择列表中的“ Employee.Ename”列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。
什么是正确的查询,可以帮助我从各个部门获取最近雇用的员工?
谢谢!
答案 0 :(得分:1)
如果这是SQL Server(假设出现该错误消息),则可以使用ROW_NUMBER()
窗口函数轻松实现这一点:
SELECT D.DName, E.EName, E.HireDate
FROM
Department D
INNER JOIN (
SELECT EmployeeNum, ENAme, HireDate, ROW_NUMBER() OVER (PARTITION BY DeptNo ORDER BY HireDate Desc) as hirerank
FROM Employee
) E ON D.DeptNo = E.DeptNo
WHERE E.hirerank = 1
答案 1 :(得分:0)
使用最大条件时必须设置group by
>
SELECT Ename,
DeptNo
, MAX(HireDate)
FROM Employee
group by Employee.Ename,DeptNo