Oracle:相关子查询中工资的标准差范围

Oracle: range of standard deviation of salary in correlated subquery

我正在使用 Oracle Developer Database,我有两个 table,员工和部门:

我应该为每个部门查找(使用相关子查询)所有员工,他们的薪水在每个部门的薪水标准差范围内。

这是我目前尝试过的方法:

SELECT d.department_name, e.employee_id, e.last_name, AVG(e.salary), e.salary
FROM hr.employees e
JOIN hr.departments d
on e.department_id = d.department_id
WHERE e.salary IN 
(SELECT salary  
FROM hr.employees 
WHERE salary > 
(SELECT ROUND(AVG(e.salary)-STDDEV(e.salary),2)
         FROM hr.employees) AND salary < (SELECT ROUND(AVG(e.salary) + STDDEV(e.salary),2) FROM hr.employees)
GROUP BY d.department_name,
e.employee_id, e.last_name, e.salary;

尽管此查询语法正确,但未显示任何结果。

其他(部分)方法有效,但我如何同时查询员工 table?

SELECT d.department_name, e.department_id, ROUND(AVG(e.salary) + STDDEV(e.salary), 2) 
AS standard_deviation_max,
ROUND(AVG(e.salary) - STDDEV(e.salary), 2) 
AS standard_deviation_min
FROM hr.employees e
JOIN hr.departments d
on e.department_id = d.department_id
GROUP BY department_name, e.department_id;

由于我是 SQL 的新手,如果有任何提示,我将不胜感激。提前谢谢你

您可以使用您的查询来查找员工详细信息,然后将工资与平均值 ± 标准差相关联:

SELECT d.department_name,
       e.employee_id,
       e.last_name,
       e.salary
FROM   hr.employees e
       JOIN hr.departments d
       on e.department_id = d.department_id
WHERE  EXISTS (
         SELECT 1
         FROM   hr.employees x
         HAVING e.salary BETWEEN AVG(e.salary) + STDDEV(e.salary)
                             AND AVG(e.salary) + STDDEV(e.salary)
       );

或者,您可以使用解析函数:

SELECT department_name,
       employee_id,
       last_name,
       salary
FROM   (
  SELECT d.department_name,
         e.employee_id,
         e.last_name,
         e.salary,
         AVG(e.salary) OVER () AS avg_salary,
         STDDEV(e.salary) OVER () AS stddev_salary
  FROM   hr.employees e
         JOIN hr.departments d
         on e.department_id = d.department_id
)
WHERE  salary BETWEEN avg_salary - stddev_salary
                  AND avg_salary + stddev_salary;