我正在尝试生成一个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%
答案 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)
以下所述查询将根据需要提供结果,而无需使用任何分析。简单&就像英语一样容易。
**
*
**
我在Oracle数据库上成功执行了此查询。