Oracle SQL 找到 5 个最低的薪水

Oracle SQL Finding the 5 lowest salaries

我正在尝试回答以下问题。显示 ID_Number 和工资最低的五名员工的姓名。

这是 table 员工:

CREATE TABLE Employees
    (ID_No          CHAR(4)     NOT NULL,
     Name           VARCHAR(50) NOT NULL,
     Hire_Date      DATE        NOT NULL,
     Position       VARCHAR(20) CHECK(Position IN('CHAIRMAN','MANAGER','ANALYST','DESIGNER','PROGRAMMER','SALES REP','ADMIN','ACCOUNTANT')),
     Salary         NUMERIC(8,2)    NOT NULL,
     Mgr_ID_No      CHAR(4)     NULL,
     Dept_No        SMALLINT    NULL);

我要补充一点,我一直在尝试一些方法,但 "limit" 和 "top" 由于某种原因不起作用。

row_number() window 函数应该在这里工作(注意 window 函数不能用在 WHERE/HAVING 子句中)。

SELECT ID_No, Name
FROM (SELECT ID_No, Name, Row_Number() OVER (ORDER BY Salary) RN
  FROM Employees)
WHERE RN <= 5;
SELECT ID_NO, NAME
FROM EMPLOYEES
ORDER BY SALARY
FETCH FIRST 5 ROWS ONLY

在 Oracle 中可以使用 ROWNUM

SELECT *
       FROM (SELECT ID_No,
                    Name
                    FROM Employees
                    ORDER BY Salary) x
       WHERE ROWNUM <= 5;

另一种方法可以是子查询,计算薪水较低或相等的行。

SELECT EO.ID_No,
       EO.Name
       FROM Employees EO
       WHERE (SELECT COUNT(*)
                     FROM Emplyoees EI
                     WHERE EI.Salary <= EO.Salary) <= 5;

Oracle 12c 中:

-- more than 5 rows being returned, if multiple rows 
-- match the value of the 5th row
SELECT e.ID_No, e.Name
  FROM Employees e
 ORDER BY e.Salary  
 FETCH FIRST 5 ROWS WITH TIES;

-- only 5 rows being returned, even if multiple rows 
-- match the value of the 5th row
SELECT e.ID_No, e.Name
  FROM Employees e
 ORDER BY e.Salary  
 FETCH FIRST 5 ROWS ONLY; 

-- NEXT clause may be replaced with FIRST  
SELECT e.ID_No, e.Name
  FROM Employees e
 ORDER BY e.Salary 
 FETCH NEXT 5 ROWS ONLY; 

Oracle 12c 之前:

SELECT e.ID_No, e.Name
  FROM ( SELECT ID_No, Name, row_number() over (order by salary) seq FROM Employees ) e
 WHERE e.seq <= 5
 ORDER BY e.seq; 

查询可用于 Top-N Queries