Oracle SQL找到5个最低工资

时间:2018-05-24 23:04:52

标签: sql database oracle

我想回答以下问题。显示五个最低薪员工的ID_Number和名称。

这是员工的表格:

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);

我将补充一点,我一直在尝试一些方法,并且"限制" " top"因某些原因不起作用。

4 个答案:

答案 0 :(得分:1)

SELECT ID_NO, NAME
FROM EMPLOYEES
ORDER BY SALARY
FETCH FIRST 5 ROWS ONLY

答案 1 :(得分:1)

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

答案 2 :(得分:-1)

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

SELECT ID_No, Name
FROM (SELECT ID_No, Name, Row_Number() OVER (ORDER BY Salary) RN
  FROM Employees)
WHERE RN <= 5;

答案 3 :(得分:-1)

在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;