我必须编写查询以返回平均薪水小于12000的部门的所有雇员。 我写下了这个查询
SELECT DEPARTMENT_ID, FIRST_NAME, LAST_NAME
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID,FIRST_NAME,LAST_NAME
HAVING AVG(SALARY) < 12000
ORDER BY LAST_NAME ASC;
但是它似乎不起作用。而不是从这些部门雇用所有员工,而是只雇用薪水低于12000的员工。 如何正确编写此查询? 预先感谢。
答案 0 :(得分:1)
您需要部门的平均工资。我会使用一个窗口函数:
SELECT DEPARTMENT_ID, FIRST_NAME, LAST_NAME
FROM (SELECT e.*, AVG(SALARY) OVER (PARTITION BY DEPARTMENT_ID) as avg_salary_dept
FROM EMPLOYEES e
) e
WHERE avg_salary_dept < 12000
ORDER BY LAST_NAME ASC;
答案 1 :(得分:0)
您需要子查询:
SELECT e.DEPARTMENT_ID, e.FIRST_NAME, e.LAST_NAME
FROM EMPLOYEES e
WHERE e.DEPARTMENT_ID IN (SELECT e1.DEPARTMENT_ID
FROM EMPLOYEES e1
GROUP BY e1.DEPARTMENT_ID
HAVING AVG(e1.SALARY) < 12000
)
ORDER BY e.LAST_NAME ASC;
答案 2 :(得分:0)
您可以使用相关子查询
SELECT e.DEPARTMENT_ID, e.FIRST_NAME, e.LAST_NAME
FROM EMPLOYEES a
WHERE exists (SELECT 1 FROM EMPLOYEES b
where a.department_id=b.department_id
HAVING AVG(b.SALARY) < 12000
);
答案 3 :(得分:0)
尝试一下。
SELECT e.DEPARTMENT_ID, e.FIRST_NAME, e.LAST_NAME
from employee e where e.DEPARTMENT_ID in
(select e.DEPARTMENT_ID from employee e
group by e.DEPARTMENT_ID
having avg(salary)<3000)