我有一个使用多个SELECTS的查询,我需要对此进行优化,但是我不知道如何执行此操作。
查询:
SELECT e.last_name, e.salary, t1.PROMEDIO
FROM employees e,
(
SELECT e.department_id, AVG(e.salary) PROMEDIO
FROM employees e
GROUP BY e.department_id
) t1
WHERE e.department_id = t1.department_id
AND e.salary < t1.PROMEDIO;
答案 0 :(得分:0)
如果我正确理解了您的问题,则您正在尝试退还薪水低于每个部门平均薪水的所有员工。如果是这样,您可以使用窗口函数avg() over()
:
select *
from (
select last_name, department_id, salary,
avg(salary) over (partition by department_id) avgsalary
from employees
) t
where salary < avgsalary
答案 1 :(得分:0)
最好使用窗口函数编写此查询:
select e.*
from (select last_name, department_id, salary,
avg(salary) over (partition by department_id) as avgsalary
from employees e
) e
where salary < avgsalary;
为了提高性能,您希望在employees(department_id, salary)
上建立索引。