使用组函数的SQL查询

时间:2019-02-12 13:43:25

标签: sql oracle oracle11g

Select department_id, max(avg(salary)) 
From employees
Group by department_id

上面的查询给出了错误

  

ORA-00937:不是单组功能

我想显示每个部门的平均薪水以及部门的最大平均薪水。有多个部门。我正在使用oracle 11g。

6 个答案:

答案 0 :(得分:1)

如果您希望部门的平均薪水最高,并且在关系平凡的情况下只希望一行,那么您只需执行以下操作:

select e.*
from (select department_id, avg(salary) as avg_salary
      from employees
      group by department_id
      order by avg(salary) desc
     ) e
where rownum = 1;

在Oracle 12C中,您不需要子查询。您可以使用fetch first 1 row only

答案 1 :(得分:1)

您的逻辑问题在于,您正在要求Oracle在单个GROUP BY中进行两个级别的聚合,而这是不可能的。作为解决方法,我们可以尝试在此处使用ROW_NUMBER

WITH cte AS (
    SELECT department_id, AVG(salary) AS avg_salary,
        ROW_NUMBER() OVER (ORDER BY AVG(salary) DESC) rn
    FROM employees
    GROUP BY department_id
)

SELECT department_id, avg_salary
FROM cte
WHERE rn = 1;

如果两个部门的平均工资最高,那么您可以用ROW_NUMBERRANK代替上面的DENSE_RANK

答案 2 :(得分:0)

您可以按照以下方式简单地重写查询。有很多方法可以实现这一目标。

Select department_id, max(avg_Salary) from (
 select department_id, avg(salary) as avg_Salary
From employees
Group by department_id)
Group by department_id

答案 3 :(得分:0)

如果您要同时选择每个部门的平均工资和最高平均工资,则应尝试以下代码:

with qr as (
    select department_id, avg(salary) as dept_avg_salary
      from employees 
     group by department_id
)
select qr.department_id
     , qr.dept_avg_salary
     , (select max(dept_avg_salary) from qr) as max_avg_salary
  from qr

希望我能帮上忙!

答案 4 :(得分:0)

要获取每个部门的平均工资以及所有部门的最大平均工资,请使用以下查询:

with sal as (
Select department_id,  avg(salary) avg_salary
From employees
Group by department_id)
select 
  DEPARTMENT_ID, AVG_SALARY,
  max(AVG_SALARY) over () MAX_AVG_SALARY
from sal 

第一个子查询是AVG_SALARY的简单聚合。 在第二步中,使用解析函数来获取平均值的全局最大值。您可以通过省略PARTITION BY子句来获得全局最大值 仅使用OVER()

答案 5 :(得分:0)

下一个查询显示每个部门的平均工资以及部门的最大平均工资

SELECT
  department_id,
  CAST(AVG(salary) AS NUMBER(8, 4)) AS dept_avg_salary,
  CAST(MAX(AVG(salary)) OVER () AS NUMBER(8, 4)) AS max_avg_salary
FROM employees
GROUP BY department_id

示例输出:

+---------------+-----------------+----------------+
| DEPARTMENT_ID | DEPT_AVG_SALARY | MAX_AVG_SALARY |
+---------------+-----------------+----------------+
|             1 | 1241.7465       | 1241.7465      |
|             2 | 1191.2267       | 1241.7465      |
|             5 | 1189.8193       | 1241.7465      |
|             4 | 1201.4198       | 1241.7465      |
|             3 | 1212.7079       | 1241.7465      |
+---------------+-----------------+----------------+

https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=a3c4057eab034ee1707f92f69125a338处进行测试。