简体   繁体   中英

What's wrong with my simple SQL query?

What is wrong with this SQL query?

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.

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. Avarage salary is selected using the alias avg_salary using the AS statement.

The outer query selects the maximum of 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 :

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!

Alternative 2, use a cte (common table expression):

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM