1

我正在尝试生成一个 SQL 查询来查找部门名称(带有员工姓名),其中有超过 2 名员工工资大于相应部门平均工资的 90%。我的 SQL 代码运行良好,没有语法错误,但输出给了我额外的数据。表如下

琼斯会计 3000
钢铁会计 2500
威尔逊研究 3000
沃尔夫研究 2500
李研究2400
兰开斯特销售额 2000
杰克逊销售额 2500
费希尔销售额 3000
亚当斯 IT 2000
米勒 IT 1000
斯科特 IT 2500
史密斯 IT 2900
国王行政 5000
约斯特执行 4500
克拉克执行官 4000

我的代码如下。

Select department_name , employee_name 
from department d , employee e 
where e.department_id = d.department_id
and (SELECT COUNT(*) 
     FROM Employee E 
     WHERE E.department_ID = D.department_ID) > 2    
    and salary > 
    0.9*(SELECT ROUND(AVG(salary),2)
    FROM employee e_inner
    WHERE e_inner.department_id = e.department_id);

我注意到我的代码返回了超过 2 名员工薪水 > 部门平均薪水 90% 的部门的值。而我正在寻找拥有超过 2 名员工且工资超过部门平均工资 90% 的部门

4

2 回答 2

1

我认为应该这样做:

select *
from (
  select department_name, 
         employee_name,
         sum(case when salary > avg_dept_sal * 0.9 then 1 else 0 end) over (partition by department_id) as greater_count
  from (
     select d.department_name,
            e.department_id,
            e.employee_name,
            e.salary,
            count(*) over (partition by e.department_id) as dept_count,
            avg(salary) over (partition by e.department_id) as avg_dept_sal
     from employee e
       join department d on e.department_id = d.department_id
  ) t1
) t2
where greater_count  >= 2

这将返回这些部门的所有员工。如果您只想查看那些薪水实际上大于 90% 的员工,则需要在外部 where 子句中添加另一个条件以仅选择这些员工。

于 2012-08-04T14:16:44.760 回答
0

下面所述的查询将在不使用任何分析的情况下根据需要给出结果。简单易懂,就像英语一样。

**

  • *
  • 将 T 设为(从员工 e1 中选择 empname、deptno、salary,其中
    薪水 >(从员工 e2 中选择 avg(salary)*0.9 where
    e2.deptno=e1.deptno group by deptno with count(empname)>2))选择 T。 empname,deptname,来自 T 的薪水,
    T.deptno=department.deptno 的部门;

*

**

我在 Oracle 数据库上成功执行了这个查询。

于 2017-05-28T04:42:18.460 回答