简体   繁体   English

使用相关查询的MSSQL Server查询

[英]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. 消息8120,级别16,状态1,行112在选择列表中的列“ Employee.Ename”无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

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: 如果这是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

You have to set group by when you are using max condition : 使用最大条件时必须设置group by

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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