员工属于部门(外键= D_ID)。员工拥有SSN(主键),姓名,薪水和D_ID。
一个部门有多名员工(主键= ID)
我想要一个查询,该查询返回部门名称|该部门最高薪雇员的姓名|他的薪水|在同一部门工作的员工的平均工资。
我知道如何选择第一部分:
SELECT
D.name, E.name, E.salary
FROM
Employee E, Department D
WHERE
salary IN (SELECT MAX(E.salary)
FROM Employee E
GROUP BY E.D_ID)
AND E.D_ID = D.ID
我也知道如何选择最后一部分:
SELECT AVG(E.salary)
FROM Employee E
GROUP BY E.D_ID
如何在单个查询中将它们放在一起?
答案 0 :(得分:0)
我会做这样的事情:
SELECT d.name
, e.name
, e.salary
, n.avg_salary
FROM Department d
JOIN ( SELECT m.d_id
, MAX(m.salary) AS max_salary
, AVG(m.salary) AS avg_salary
FROM Employee m
GROUP BY m.d_id
) n
ON n.d_id = d.id
JOIN Employee E
ON e.d_id = d.id
AND e.salary = n.max_salary
答案 1 :(得分:0)
您可以为此使用窗口功能:
select department_name, employee_name, salary, avg_dept_salary
from (
select e.name as employee_name,
d.name as department_name,
e.salary,
max(e.salary) over (partition by d.id) as max_dept_salary,
avg(e.salary) over (partition by d.id) as avg_dept_salary
from Employee E
join Department D on e.d_id = d.id
) t
where salary = max_dept_salary
order by department_name;
以上是标准的ANSI SQL,可以在所有现代DBMS上运行。