[英]What's wrong with my simple SQL query?
What is wrong with this SQL query?这个 SQL 查询有什么问题?
SELECT
department_id, MAX(AVG(SALARY))
FROM
EMPLOYEES
GROUP BY
department_id;
It shows not a single-group group function它显示不是单组组功能
2 Aggregate functions in one Query can not be done, you should use a Subquery to achieve your result. 2 一个查询中的聚合函数无法完成,您应该使用子查询来实现您的结果。
I've not possibility to test it right now so no guarantees on this query but you may get an idea.我现在无法对其进行测试,因此无法保证此查询,但您可能会有所了解。
select max (avg_salary)
from (select department_id, avg(SALARY) AS avg_salary
from EMPLOYEES
group by department_id);
The inner query selects deparment_id and average salary.内部查询选择 deparment_id 和平均工资。 Avarage salary is selected using the alias avg_salary using the AS statement.
平均工资是使用 AS 语句使用别名 avg_salary 选择的。
The outer query selects the maximum of avg_salary-外部查询选择 avg_salary- 的最大值
That's maybe not a complete solution to your problem and as I said, not tested so no guarantees, but you should have an idea now how to start.这可能不是您问题的完整解决方案,正如我所说,未经测试,因此无法保证,但您现在应该知道如何开始。 ;-)
;-)
You cant have more than one aggregate functions in one query.一个查询中不能有多个聚合函数。 try this one
试试这个
select dept, max(average) over (partition by dept)
from (SELECT department_id dept,
(AVG(SALary) OVER (PARTITION BY department_id)) average
FROM employees);
Alternative 1, double GROUP BY
:备选方案 1,双
GROUP BY
:
SELECT department_id, AVG(SALARY)
FROM EMPLOYEES
GROUP BY department_id
HAVING AVG(SALARY) = (select max(avg_sal)
from (select avg(salary) as avg_sal
from EMPLOYEES
group by department_id))
Will return both department_id
's if there's a tie!如果有平局,将返回两个
department_id
!
Alternative 2, use a cte (common table expression):备选方案2,使用cte(公用表表达式):
with
(
SELECT department_id, AVG(SALARY) as avg_sal
FROM EMPLOYEES
GROUP BY department_id
) as cte
select department_id, avg_sal
from cte
where avg_sal = (select max(avg_sal) from cte)
This too will return both department_id
's if there's a tie!如果有平局,这也将返回两个
department_id
id !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.