聚合函数并在 2 个条件下加入
Posted
技术标签:
【中文标题】聚合函数并在 2 个条件下加入【英文标题】:Aggregate function and join on 2 conditions 【发布时间】:2018-01-27 16:52:50 【问题描述】:我有 Oracle 的这个任务。它要求我显示部门名称(部门是一个包含该表的 manager_id、department_id 和部门名称的表)、该部门的 manager_id、经理的姓名(在雇员表中找到)和该部门的平均工资(每个员工的工资也可以在员工中找到)。一旦我尝试检索经理姓名(我想通过将他的部门 ID 与员工的 ID 进行比较),它就会弄乱我的平均值。没有它(如下所示)它工作得很好
SELECT d.department_name, AVG(e.salary) as "Salaries"
FROM employees e join departments d on e.department_id=d.department_id
WHERE d.manager_id=e.employee_id
GROUP BY e.department_id, d.department_name,d.manager_id
ORDER BY AVG(e.salary)
谁能帮我解决这个问题,或者解释一下我为什么搞砸了?
【问题讨论】:
在加入部门之前在子查询中计算出你的平均值。 更新您的问题广告适当的数据样本和预期结果 【参考方案1】:WITH factoring 子句选择平均工资;然后将其连接到其他表
SQL> with avgsal as
2 (select e.department_id, round(avg(e.salary)) avg_sal
3 from employees e
4 group by e.department_id
5 )
6 select d.department_id,
7 d.department_name,
8 m.last_name manager,
9 a.avg_sal
10 from departments d
11 join employees m on m.department_id = d.department_id
12 and m.employee_id = d.manager_id
13 join avgsal a on a.department_id = d.department_id
14 order by a.avg_sal;
DEPARTMENT_ID DEPARTMENT_NAME MANAGER AVG_SAL
------------- -------------------- ------------------------- ----------
50 Shipping Fripp 3476
30 Purchasing Raphaely 4150
10 Administration Whalen 4400
60 IT Hunold 5760
40 Human Resources Mavris 6500
100 Finance Greenberg 8601
80 Sales Russell 8956
20 Marketing Hartstein 9500
70 Public Relations Baer 10000
110 Accounting Higgins 10154
90 Executive King 19333
11 rows selected.
SQL>
快速检查 2 个部门:
SQL> select department_id, round(avg(salary)) avg_sal, count(*) "# of employees"
2 from employees
3 where department_id in (20, 30)
4 group by department_id
5 order by 1;
DEPARTMENT_ID AVG_SAL # of employees
------------- ---------- --------------
20 9500 2
30 4150 6
SQL>
【讨论】:
不客气!现在,请点击这里***.com/help/someone-answers。【参考方案2】:在查询的经理姓名选择中引入相关子查询。
SELECT d.department_name,
AVG(e.salary) AS "Salaries",
(SELECT first_name
||' '
||last_name
FROM employees i
WHERE i.employee_id = d.manager_id) AS manager_name
FROM employees e
join departments d
ON e.department_id = d.department_id
GROUP BY e.department_id,
d.department_name,
d.manager_id
ORDER BY Avg(e.salary);
【讨论】:
除非我错了,否则不会产生正确的结果。在 HR 模式中,对于“市场营销”部门,你得到 13000(应该是 9500)。或者,“采购”——你得到了 11000,应该是 4150。等等。 @Littlefoot :对。OP 的 sql 中的where
子句是不必要的,并且会破坏平均值。我已将其删除。以上是关于聚合函数并在 2 个条件下加入的主要内容,如果未能解决你的问题,请参考以下文章