两个聚合函数分组

时间:2015-04-27 20:42:16

标签: sql oracle

我正在尝试打印所有工资总额大于部门平均金额的部门名称。

enter image description here

SELECT d.department_name, SUM(e.salary)
FROM departments d, employees e
WHERE d.department_id = e.department_id
GROUP BY d.department_name
HAVING SUM(e.salary) > (SELECT AVG(SUM(salary)) from employees);

在第二个选择中,我需要按AVG(SUM(salary))分组?

2 个答案:

答案 0 :(得分:1)

您需要在条件中重复第一个查询。这可以使用WITH子句来完成。

WITH dept_sums AS (SELECT d.department_name, SUM(e.salary) sum_salary
FROM departments d, employees e
WHERE d.department_id = e.department_id
GROUP BY d.department_name)

SELECT * FROM dept_sums d_s_1 WHERE d_s_1.sum_salary > (SELECT AVG(sum_salary) FROM dept_sums d_s_2);

答案 1 :(得分:1)

这是窗口(分析)功能派上用场的地方。下面我使用SELECT department_name, dept_salary FROM ( SELECT d.department_name, SUM(e.salary) AS dept_salary , AVG(SUM(e.salary)) OVER ( ) AS avg_dept_salary FROM departments d INNER JOIN employees e ON d.department_id = e.department_id GROUP BY d.department_name ) WHERE dept_salary > avg_dept_salary; 作为分析函数来计算所有部门的平均总薪水。

adb install