【问题标题】:Department names(with employee name) with more than 2 employee and salary greater than 90% of respective department average salary部门名称(含员工姓名),员工人数超过 2 人,工资高于各部门平均工资的 90%
【发布时间】:2012-08-02 07:13:13
【问题描述】:

我正在尝试生成一个 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%

【问题讨论】:

  • 区分大小写吗?您是否需要 E 以外的别名与 e 不同?
  • 它不区分大小写。我的输出应该只给我 2 个部门,在这个阶段给我 4 个。

标签: sql oracle


【解决方案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 子句中添加另一个条件以仅选择这些员工。

【讨论】:

  • @Gary1266:查看我的编辑。顺便说一句,如果这是家庭作业,请告诉我们。
  • 这是标准txtbook每章末尾给出的练习题,但是由于我刚刚开始编写SQL代码,所以我有点挣扎。此问题的输出如下 IT RESEARCH 感谢您的帮助
【解决方案2】:

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

**

  • *
  • T 为(从员工 e1 中选择 empname、deptno、salary
    薪水 > (select avg(salary)*0.9 from employee e2 where
    e2.deptno=e1.deptno group by deptno count(empname)>2)) 选择 T.empname、deptname、T 的薪水、所在部门
    T.deptno=department.deptno;

*

**

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

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2023-03-22
    • 2019-01-25
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多