部门名称(员工姓名),员工人数超过2人,工资超过各部门平均工资的90%

时间:2012-08-04 14:05:36

标签: sql oracle

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

JONES         ACCOUNTING    3000
STEEL         ACCOUNTING    2500
WILSON        RESEARCH      3000
WOLFE         RESEARCH      2500
LEE           RESEARCH      2400
LANCASTER     SALES         2000
JACKSON       SALES         2500
FISHER        SALES         3000
ADAMS         IT            2000
MILLER        IT            1000
SCOTT         IT            2500
SMITH         IT            2900
KING          EXECUTIVE     5000
JOST          EXECUTIVE     4500
CLARK         EXECUTIVE     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%

2 个答案:

答案 0 :(得分: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子句中添加另一个条件,以便仅选择那些。

答案 1 :(得分:0)

以下所述查询将根据需要提供结果,而无需使用任何分析。简单&就像英语一样容易。

**

  • *
  • 用T as(选择empname,deptno,员工e1的薪水,其中
    工资> (从员工e2中选择avg(薪水)* 0.9,其中
    e2.deptno = e1.deptno group by deptno,具有count(empname)> 2))select T.empname,deptname,工资来自T,部门所在 T.deptno = department.deptno;

*

**

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