一条SQL语句根据另一个值的结果来查找一个值

时间:2019-05-01 18:31:21

标签: sql-server

在不使用子查询的情况下,我尝试先找到特定部门的经理,然后再找到该部门经理的经理。这可能吗?还是需要子查询?

SELECT M. EmployeeFirstName, M. EmployeeLastName
FROM EMPLOYEE_t M, EMPLOYEE_t E
WHERE E.ManagerID = M.EmployeeID
AND E.EmployeeJobTitle = 'Accountant'
GROUP BY M. EmployeeFirstName, M. EmployeeLastName

提供的这段代码返回部门经理,但是我不确定如何在单个语句中找到该部门经理的经理。

2 个答案:

答案 0 :(得分:0)

只需继续加入Employee_t。另外两件事:

  1. 我不确定您是否需要GROUP BY
  2. 使用ANSI-92连接
SELECT M.EmployeeFirstName
     , M.EmployeeLastName
     , M2.EmployeeFirstName AS ManagerFirstName
     , M2.EmployeeLastName  AS ManagerLastName
FROM EMPLOYEE_t E
JOIN EMPLOYEE_t M
  ON E.ManagerID = M.EmployeeID
JOIN EMPLOYEE_t M2
  ON M.ManagerID = M2.EmployeeID
WHERE E.EmployeeJobTitle = 'Accountant'

答案 1 :(得分:0)

这里是对当前查询的重写,该查询检索使用INNER JOIN(ANSI-92语法)重写的会计师经理的经理的姓名

SELECT 
    MM.EmployeeFirstName, 
    MM.EmployeeLastName
FROM EMPLOYEE_t M
INNER JOIN EMPLOYEE_t E
    ON E.ManagerID = M.EmployeeID
INNER JOIN EMPLOYEE_t MM
    ON M.ManagerId = MM.EmployeeID
WHERE E.EmployeeJobTitle = 'Accountant'
GROUP BY MM.EmployeeFirstName, MM.EmployeeLastName

在查询顶部可以用关键字DISTINCT代替GROUP BY的使用,以便只返回每个管理者一次,例如

SELECT DISTINCT
    MM.EmployeeFirstName, 
    MM.EmployeeLastName
FROM EMPLOYEE_t M
INNER JOIN EMPLOYEE_t E
    ON E.ManagerID = M.EmployeeID
INNER JOIN EMPLOYEE_t MM
    ON M.ManagerId = MM.EmployeeID
WHERE E.EmployeeJobTitle = 'Accountant'

此外,如果并非所有会计师的经理都拥有经理,则可能要返回可以找到的最高级别经理的名称。在这种情况下,您可以使用ISNULL()LEFT JOIN返回正确的顶级管理员名称,即

SELECT DISTINCT
    ISNULL(MM.EmployeeFirstName, M.EmployeeFirstName) as EmployeeFirstName,
    ISNULL(MM.EmployeeLastName, M.EmployeeLastName) as EmployeeLastName
FROM EMPLOYEE_t M
INNER JOIN EMPLOYEE_t E
    ON E.ManagerID = M.EmployeeID
LEFT JOIN EMPLOYEE_t MM
    ON M.ManagerId = MM.EmployeeID
WHERE E.EmployeeJobTitle = 'Accountant'