简体   繁体   English

如何通过多选优化SQL查询

[英]How to optimize SQL query with multiple selects

I have a query that uses multiple SELECTS, and I need to optimize this but I have no clue how to do this. 我有一个使用多个SELECTS的查询,我需要对此进行优化,但是我不知道如何执行此操作。

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() : 如果是这样,您可以使用窗口函数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) . 为了提高性能,您需要一个有关employees(department_id, salary)的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM