SELECT
departments.department_id,
department_name,
departments.manager_id,
first_name,
max(salary) as Maximum_Salary,
min(salary) Minimum_Salary
FROM departments,employees
WHERE departments.department_id = employees.department_id
AND departments.manager_id = employee_id
GROUP BY departments.department_id, department_name,
departments.manager_id, first_name
ORDER BY department_id;
SELECT
departments.department_id,
department_name,
departments.manager_id,
max(salary) as Maximum_Salary,
min(salary) Minimum_Salary
FROM departments,employees
WHERE departments.department_id = employees.department_id
GROUP BY departments.department_id, department_name, departments.manager_id
ORDER BY department_id;
我尝试过两次查询。我每次都得到经理的工资,而不是部门的最高和最低工资,但是如果我从第一个查询中删除'first_name'并修改join子句,那么答案是对的(即第二个查询),但我想得到经理的名字。
答案 0 :(得分:0)
您需要选择员工表,如下所示: employees.salary 和 employees.first_name 。
查询将如下所示:
select departments.department_id,department_name,departments.manager_id,employees.first_name,max(employees.salary) as Maximum_Salary,min(employees.salary) Minimum_Salary from departments,employees where departments.department_id=employees.department_id and departments.manager_id=employee_id group by departments.department_id,department_name,departments.manager_id,first_name order by department_id;
答案 1 :(得分:0)
您必须为employees表创建两个JOIN:首先在employee和manager_id之间进行联接,然后在employee和department_id之间进行第二次联接。
这样的事情应该有效:
SELECT
d.department_id,
d.department_name,
d.manager_id,
m.first_name,
max(e.salary) as Maximum_Salary,
min(e.salary) Minimum_Salary
FROM departments d
LEFT JOIN employees e ON d.department_id=e.department_id
LEFT JOIN employees m ON d.manager_id = m.employee_id
GROUP BY d.department_id, d.department_name,
d.manager_id, m.first_name
ORDER BY d.department_id;
答案 2 :(得分:0)
您可以使用外部申请按部门ID获取最低和最高工资,并将其应用于经理信息。
SELECT d.department_id,
d.department_name,
d.manager_id,
m.first_name,
s.Maximum_Salary,
s.Minimum_Salary
FROM departments d
INNER JOIN employees m ON m.employee_id = d.manager_id
OUTER APPLY (SELECT MAX(salary) Maximum_Salary,
MIN(salary) Minimum_Salary
FROM employees e
WHERE e.department_id = d.department_id
) s
ORDER BY d.department_id
如果您的dbms不支持外部应用..左连接也将起作用
SELECT d.department_id,
d.department_name,
d.manager_id,
m.first_name,
s.Maximum_Salary,
s.Minimum_Salary
FROM departments d
INNER JOIN employees m ON m.employee_id = d.manager_id
LEFT JOIN (SELECT e.department_id,
MAX(salary) Maximum_Salary,
MIN(salary) Minimum_Salary
FROM employees e
GROUP BY e.department_id
) s ON s.department_id = d.department_id
ORDER BY d.department_id