最高平均值

时间:2010-03-13 19:07:01

标签: sql oracle oracle10g ora-00937

我应该得到每个部门的平均工资,并且只显示平均工资最高的部门。我想出了这个查询,但它不起作用。有人有想法吗?

SELECT department, max(avg(wage))
FROM employees
GROUP BY department;

我收到此错误: 第1行的错误: ORA-00937:不是单组组功能

4 个答案:

答案 0 :(得分:4)

如果没有CTE,您可以这样做:

Select Z.Department, Z.AvgWage
From  (
        Select Department, Avg(Wage) AvgWage
        From Employees
        Group By Department
        ) As Z
Where AvgWage = (
                Select Max(Z1.AvgWage)
                From    (
                        Select Department, Avg(Wage) AvgWage
                        From Employees
                        Group By Department
                        )  Z1
                )

使用CTE,您可以:

With AvgWages As
    (
    Select Department
        , Avg(Wage) AvgWage
        , Rank() Over( Order By Avg(Wage) Desc ) WageRank
    From Employees
    Group By Department
    )
Select Department, AvgWage, WageRank
From AvgWages
Where WageRank = 1

答案 1 :(得分:3)

这样做有效:

select *
from
(
  SELECT 
      department
      , avg(wage) as ave_wage
  FROM employees 
  GROUP BY department
)x 
order by ave_wage desc 
where rownum < 2;

(免责声明:完全未经测试,所以我可能将rownum位置放在错误的位置)

答案 2 :(得分:1)

Althogh下面的查询显示与其他答案相同的结果,很高兴向用户展示如何将其作为替代方案:

--Method 1 (Davek's select of 1st row over Order by) Brilliant!
--Method 2 (Thomas' where = sub-query result)
--Method 3 (Thomas' based on ranking)

--Method 4 (Inner join sub-queries)
select distinct a.department, a.wage from 
         (select distinct department, AVG(wage) as wage from employees group by department) as a
   inner join 
         (select Max(wage) as wage from
                (select distinct department, AVG(wage) as wage from employees group by department) as x) as b
   on a.wage = b.wage 
where a.wage = b.wage 

--Method 5 (AVG wage in (sub-query))
select distinct a.department, a.wage
from (select distinct department, AVG(wage) as wage from employees group by department) as a
Where a.wage in 
    (select Max(wage) as wage from
        (select distinct department, AVG(wage) as wage from employees group by department) as x)

期待看到这个选择的自定义功能:)

答案 3 :(得分:0)

通过谷歌搜索...

原因:SELECT列表不能同时包含组函数,如AVG,COUNT,MAX,MIN,SUM,STDDEV或VARIANCE,以及​​单个列表达式,除非GROUP BY子句中包含单个列表达式

操作:从SELECT列表中删除组函数或单个列表达式,或添加包含列出的所有单个列表达式的GROUP BY子句。