两个聚合函数分组
Posted
技术标签:
【中文标题】两个聚合函数分组【英文标题】:Two aggregation functions group by 【发布时间】:2015-04-27 20:42:16 【问题描述】:我正在尝试打印所有工资总和大于部门平均总和的部门名称。
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))
分组吗?
【问题讨论】:
查看使用窗口集(Over partition by),这可以让您通过选择获得平均内联。示例:oracle-base.com/articles/misc/analytic-functions.php 或者:***.com/questions/6847814/… 【参考方案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);
【讨论】:
【参考方案2】:这是窗口(分析)函数派上用场的地方。下面我使用AVG()
作为解析函数来计算所有部门的平均总工资。
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;
【讨论】:
以上是关于两个聚合函数分组的主要内容,如果未能解决你的问题,请参考以下文章
pandas使用groupby函数agg函数获取每个分组聚合对应的均值(mean)实战:计算分组聚合单数据列的均值计算分组聚合多数据列的均值