我不知道如何纠正这个SQL练习

时间:2019-03-19 19:35:53

标签: sql oracle

我正在使用ORACLE,并且此查询是在HR模式中完成的。我的问题是此查询并不完美,我迷路了,不知道如何继续。 (请不要像您做作业那样粗鲁,因为我只会在尝试过东西时询问)。顺便说一句,这些陈述是西班牙语的,但我翻译了它们。

1.永久性媒体部门的高级职务和常任理事长。
英语:超过其所属部门的平均工资的雇员的雇员姓名和部门名称。

select e.first_name, e.last_name, d.department_name
    from employees e
    INNER JOIN departments d ON e.department_id = d.department_id
    where salary > (select avg(salary)
                        from employees
                        where department_id = department_id);
  1. Empleados que,en cada departamento,tienen el sueldomáximo。
    英语:每个部门中薪水最高的员工
select e.employee_id
    from employees e
    INNER JOIN departments d ON e.department_id = d.department_id
    where salary = (select hire_date
                        from employees
                        where employee_id = 107);
  1. Empleados que trabajen en departamentos en los que nadie cobre comisiones。
    英语:在没有人收取佣金的部门工作的员工
select e.employee_id
    from employees e
    INNER JOIN departments d ON e.department_id = d.department_id
    where commission_pct = (select sum(commission_pct)
                                from employees
                                group by department_id
                                having sum(commission_pct) = 0);
  1. Taragao的第3部门,tra saljarios的总称,comisiones y的总称 努马罗-德特拉巴贾多雷斯。 Mostrar el nombre del departamento y las 3 candidades。
    英语:对于每个有3个或更多工人的部门,请计算总工资,佣金总额和 工人人数。显示部门名称和3个数量
select sum(e.salary), sum(e.commission_pct), count(e.employee_id), d.department_name
    from employees e
    INNER JOIN departments d ON e.department_id = d.department_id
    where count(e.employee_id) >= 3;

1 个答案:

答案 0 :(得分:2)

在大多数情况下,您都非常亲密。


从1开始:应该始终使用表别名。如果不这样做,结果将是不可预测的,并且很可能是错误的。应该是:

select e.first_name, e.last_name, d.department_name
    from employees e
    INNER JOIN departments d ON e.department_id = d.department_id
    where e.salary > (select avg(e1.salary)
                        from employees e1
                        where e1.department_id = d.department_id);  --> aliases, especially here!

截至5:您的查询没有意义;怎么样?

select d.department_name, e.employee_id
from employees e INNER JOIN departments d ON e.department_id = d.department_id
where e.salary = (select max(e1.salary) 
                  from employees e1
                  where e1.department_id = d.department_id);

截至8:

select e.employee_id, d.department_name
    from employees e
    INNER JOIN departments d ON e.department_id = d.department_id
where e.department_id in (select e1.department_id
                          from employees e1
                          group by e1.department_id
                          having sum(commission_pct) is null;

截至10:

select sum(e.salary), sum(e.commission_pct), count(e.employee_id), d.department_name
    from employees e
    INNER JOIN departments d ON e.department_id = d.department_id
    group by d.department_name
    having count(*) >= 3;