简体   繁体   中英

MSSQL Server Query using correlated query

I have two tables:

Employee(EmployeeNum, Ename, Job, MGR, HireDate, SAL,COMM, DeptNo)
Department (DeptNo, DName, LOC)

I am trying to find the following:

Q. Who is the most recently hired employee in each department?

The Query is:

SELECT Employee.Ename,
(SELECT MAX(HireDate)
FROM Department
WHERE Employee.DeptNo = Department.DeptNo)
AS HireDate
FROM Employee;

But I am getting the following error:

Msg 8120, Level 16, State 1, Line 112 Column 'Employee.Ename' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

What is the correct query that will help me to obtain the most recently hired employee from each department?

Thanks!

If this is SQL Server (assuming from that error message) you can use ROW_NUMBER() window function to get at this pretty easily:

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

You have to set group by when you are using max condition :

     SELECT Ename,
     DeptNo
    , MAX(HireDate)
    FROM Employee
    group by Employee.Ename,DeptNo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM