我正在使用Oracle db 11g
我有一张桌子' EMPLOYEES'像这样...
ID JOB_ID SALARY
100 AD_PRES 24000
101 AD_VP 17000
102 AD_VP 17000
103 IT_PROG 9000
104 IT_PROG 6000
107 IT_PROG 4200
124 ST_MAN 5800
141 ST_CLERK 3500
142 ST_CLERK 3100
143 ST_CLERK 2600
144 ST_CLERK 2500
149 SA_MAN 10500
174 SA_REP 11000
176 SA_REP 8600
178 SA_REP 7000
200 AD_ASST 4400
201 MK_MAN 13000
202 MK_REP 6000
205 AC_MGR 12000
206 AC_ACCOUNT 8300
我希望得到每份工作(job_id)的最高平均工资及其工作。
我首先尝试了这个并导致错误
SELECT MAX(AVG(salary)) AS max_avg_salary, job_id
FROM employees
GROUP BY job_id;
ORA-00937: not a single-group group function
00937. 00000 - "not a single-group group function"
*Cause:
*Action:
我终于使用此代码
了WITH emp AS (SELECT AVG(salary) AS avg_salary, job_id FROM employees GROUP BY job_id)
SELECT e1.avg_salary AS max_avg_salary, e1.job_id
FROM emp e1 JOIN (SELECT MAX(avg_salary) AS max_avg_salary FROM emp) e2
ON e1.avg_salary = e2.max_avg_salary;
MAX_AVG_SALARY JOB_ID
24000 AD_PRES
我想知道的是......
答案 0 :(得分:3)
这个怎么样?
select job_id, salary
from ( select job_id,
avg (salary) salary,
rank () over (order by avg (salary) desc) rnk
from employees
group by job_id)
where rnk = 1;
答案 1 :(得分:1)
[已编辑] ...除非您只想获得一个答案,否则其他受访者的解决方案应该有效,我会提供一个变体:
<强>非Oracle:强>
SELECT TOP 1 *
FROM
(SELECT AVG(salary) AS avg_salary, job_id
FROM employees
GROUP BY job_id
) a
ORDER BY a.avg_salary DESC
Littlefoot非常正确地指出,由于TOP 1,这对Oracle 无效。你应该选择他的解决方案。对于任何非甲骨文的人,我都会留在这里:
然而,提问者本人,C Park,使用ROWNUM建议使用与Oracle兼容的变体。他已经对它进行了测试,它对他有用,所以这将有效。
<强>甲骨文:强>
SELECT *
FROM
(SELECT AVG(salary) AS avg_salary, job_id
FROM employees
GROUP BY job_id
) a
ORDER BY a.avg_salary DESC
WHERE ROWNUM = 1
我希望这会有所帮助。
答案 2 :(得分:1)
您可以像这样修改您的查询,
SELECT MAX(avg_salary)
FROM (SELECT AVG(salary) AS avg_salary, job_id
FROM employees
GROUP BY job_id);
或者如果您还要显示作业ID,
SELECT avg_salary, job_id
FROM (SELECT AVG(salary) AS avg_salary, job_id
FROM employees
GROUP BY job_id
ORDER BY avg_salary DESC)
WHERE ROWNUM = 1;