我应该得到每个部门的平均工资,只显示平均工资最高的部门。我想出了这个查询,但它不起作用。有人有什么想法吗?
SELECT department, max(avg(wage))
FROM employees
GROUP BY department;
我收到此错误:第 1 行的错误:ORA-00937:不是单组组函数
如果没有 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
这个工作:
select *
from
(
SELECT
department
, avg(wage) as ave_wage
FROM employees
GROUP BY department
)x
order by ave_wage desc
where rownum < 2;
(免责声明:完全未经测试,所以我可能将 rownum 位放在了错误的位置)
尽管下面的查询显示与其他答案相同的结果,但很高兴向用户展示如何作为替代方法完成:
--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)
也期待看到此选择的自定义功能:)
通过谷歌搜索...
原因:一个 SELECT 列表不能同时包含一个组函数,例如 AVG、COUNT、MAX、MIN、SUM、STDDEV 或 VARIANCE,以及一个单独的列表达式,除非单独的列表达式包含在 GROUP BY 子句中。
行动:从 SELECT 列表中删除组函数或单个列表达式,或添加一个 GROUP BY 子句,其中包括列出的所有单个列表达式。