SQL - SELECTING MAX返回不同的列

时间:2017-09-08 03:14:00

标签: sql database

我的问题是代码是代码返回包括经理在内的员工的最高工资 当我希望它排除经理时。

除此之外它还有效。

这是我写的代码:

SELECT firstname || ' ' || lastname 
AS "FULL NAME"
FROM EMPLOYEES
WHERE salary = 
    ( SELECT MAX(salary)
        FROM EMPLOYEES, DEPARTMENTS 
        WHERE NOT employee_id = manager_id);

这是数据库架构

COUNTRIES(country_id, country_name, region) 
• Primary key: {country_id}

DEPARTMENTS(department_id, department_name, manager_id)
• Primary key: {department_id }
• Foreign key: [manager_id]  ⊆ EMPLOYEES[employee_id]

DEPT_LOCATIONS(department_id, city, country_id)
• Primary key: {department_id, city}
• Foreign key: [department_id]  ⊆ DEPARTMENTS[department_id] and 
[country_id]  ⊆ COUNTRIES[country_id]

EMPLOYEES(employee_id, firstname, lastname, email, phone_no, salary, 
department_id)
• Primary key: {employee_id}
• Foreign key: [department_id]  ⊆ DEPARTMENTS[department_id]

任何帮助都非常感激。

2 个答案:

答案 0 :(得分:1)

如果您的子查询按部门选择最高工资,那么您可以加入该结果以按部门获取您的列表。

SELECT firstname || ' ' || lastname AS "FULL NAME",
       E.department_id
FROM EMPLOYEES E
JOIN (
  SELECT E.department_id, MAX(E.salary) as MAX_SALARY
  FROM EMPLOYEES E
  JOIN DEPARTMENTS D ON E.department_id = D.department_id
  WHERE employee_id <> manager_id
  GROUP BY E.department_id 
) AS M ON M.MAX_SALARY = E.salary AND E.department_id = M.department_id 

如果您不按部门要求,它看起来像这样:

SELECT firstname || ' ' || lastname AS "FULL NAME"
FROM EMPLOYEES E
JOIN (
  SELECT MAX(E.salary) as MAX_SALARY
  FROM EMPLOYEES E
  JOIN DEPARTMENTS D ON E.department_id = D.department_id
  WHERE employee_id <> manager_id
) AS M ON M.MAX_SALARY = E.salary 

答案 1 :(得分:0)

这个怎么样?

SELECT e.firstname || ' ' || e.lastname 
AS "FULL NAME"
FROM EMPLOYEES e
WHERE e.salary = 
    ( SELECT MAX(salary)
        FROM EMPLOYEES, DEPARTMENTS 
        WHERE NOT employee_id = manager_id)
AND NOT EXISTS (SELECT 1 FROM DEPARTMENTS d WHERE e.employee_id = d.manager_id)

您只需过滤结果