オラクルのemp
テーブルで上位3位の給与を見つける方法は?
SELECT *FROM
(
SELECT *FROM emp
ORDER BY Salary desc
)
WHERE rownum <= 3
ORDER BY Salary ;
あなたが試すことができます。
SELECT * FROM
(
SELECT EMPLOYEE, LAST_NAME, SALARY,
RANK() OVER (ORDER BY SALARY DESC) EMPRANK
FROM emp
)
WHERE emprank <= 3;
これにより、同じ最大給与を持つ2人の従業員がいる場合でも、正しい出力が得られます。
SELECT a.ename, b.sal
FROM emp a, emp b
WHERE a.empno = b.empno
AND
3 > (SELECT count(*) FROM emp b
WHERE a.sal = b.sal);
TOP、ROWID、ランクなどを使用せずに、最も古いSQLでも動作します
次のようなものがそれを行うはずです。
SELECT Name, Salary
FROM
(
SELECT Name, Salary
FROM emp
ORDER BY Salary desc
)
WHERE rownum <= 3
ORDER BY Salary ;
Select ename, job, sal from emp
where sal >=(select max(sal) from emp
where sal < (select max(sal) from emp
where sal < (select max(sal) from emp)))
order by sal;
ENAME JOB SAL
---------- --------- ----------
KING PRESIDENT 5000
FORD ANALYST 3000
SCOTT ANALYST 3000
SELECT * FROM
(
SELECT EMPLOYEE, LAST_NAME, SALARY,
DENSE_RANK() OVER (ORDER BY SALARY DESC) EMPRANK
FROM emp
)
WHERE emprank <= 3;
SET SERVEROUTPUT ON;
DECLARE
s DBMS_STAT_FUNCS.SummaryType;
BEGIN
DBMS_STAT_FUNCS.SUMMARY('HR', 'EMPLOYEES', 'SALARY',3, s);
DBMS_OUTPUT.put_line('Top 3: ' || s.top_5_values(1) || '-'
|| s.top_5_values(2) || '-' || s.top_5_values(3));
END;
/
出力:
Top 3: 24000-17000-17000