I have a query that uses multiple SELECTS, and I need to optimize this but I have no clue how to do this.
Query:
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;
If I'm understanding your question correctly, you are trying to return all employees whose salary is less than the average salary per department. If so, you can use the window function avg() over()
:
select *
from (
select last_name, department_id, salary,
avg(salary) over (partition by department_id) avgsalary
from employees
) t
where salary < avgsalary
It is better to write this query using window functions:
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;
For performance, you want an index on employees(department_id, salary)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.