使用SCOTT Schema。我想让薪水最接近平均水平的人。
SELECT sal
FROM ( SELECT sal
FROM emp
ORDER BY ABS ( (SELECT AVG (SAL) FROM EMP) - sal))
WHERE ROWNUM = 1;
上述解决方案能否得到改善?
答案 0 :(得分:2)
with av as (select avg(sal) avgsal from scott.emp)
select emp.*, abs(emp.sal-av.avgsal) dist
from scott.emp, av
order by dist;
上面看起来对我来说更好,但可能你可以通过分析功能获得最佳效果。类似的东西:
select * from (
select emp.*, abs(avg(emp.sal) over () - sal) diff
from scott.emp order by diff)
where rownum = 1;
答案 1 :(得分:2)
使用子查询拉回员工数据:
select empno, sal, SalDif
from
(
select empno, sal, abs(sal - (select avg(sal) from emp)) as SalDif
from emp
order by SalDif
)
where rownum = 1;
或作为CTE:
with CTE as
(
select empno, sal, abs(sal - (select avg(sal) from emp)) as SalDif
from emp
order by SalDif
)
select empno, sal, SalDif
from CTE
where rownum = 1;
答案 2 :(得分:2)
您使用的是非标准Oracle功能。子查询中的数据最初没有订单,但在Oracle中您可以对其进行订购,以便以后能够应用ROWNUM标准。 ROWNUM也是Oracle特有的。
此外,可能有几名员工薪水相同,您可以随意挑选其中一名,而不是全部展示。
以下是如何在标准SQL中选择薪酬最接近avarage的员工:
select *
from emp
order by abs(sal - avg(sal) over())
fetch first row with ties;
最后一行仅适用于Oracle 12c。
在旧版本(即Oracle 9i,10i或11g)中,您可以改为对行进行排名:
select empno, ename, sal
from
(
select empno, ename, sal, rank() over (order by diff) as rnk
from
(
select emp.*, abs(sal - avg(sal) over()) as diff
from emp
) evaluated
) ranked
where rnk = 1;