2010-03-13 240 views
3

我應該得到每個部門的平均工資,只顯示平均工資最高的部門。我想出了這個查詢,但它不起作用。任何人有一些想法?最大平均值

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

我得到這個錯誤: ORA-00937:第1行 錯誤不是一個單一羣組功能

回答

0

谷歌搜索...

原因:SELECT列表不能包括除非單個列表達式包含在GROUP BY子句中,否則都是一個組函數,例如AVG,COUNT,MAX,MIN,SUM,STDDEV或VARIANCE以及單個列表達式。

操作:從SELECT列表中刪除組函數或單個列表達式,或者添加包含列出的所有單個列表達式的GROUP BY子句。

+1

這不是很有幫助...代碼示例是一個更好的方法。 – 2010-03-13 19:10:34

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位在錯誤的地方)

+0

這樣做的技巧,謝謝! – 2010-03-13 19:22:19

+0

如果平均值最高的平均值是多少?這將隨機挑選其中一個。那是你要的嗎? – 2010-03-14 04:05:05

+0

這讓我有一天,很棒!我仍然無法將它複製到MSSQL,因爲它不喜歡rownum。基於這個概念,你也可以使用'select Top(1)* from(...)',它像MSSQL中的一個魅力一樣工作(如果在表格上播放,填充AVG查詢) – Takedasama 2013-11-27 14:09:18

2

沒有熱膨脹係數,你可以這樣做:

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

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) 

期待看到一個自定義函數爲這個選擇也:)

相關問題