Oracle SQL Finding the 5 lowest salaries

南楼画角 提交于 2019-12-31 05:10:47

问题


I am trying to answer the following question. Show ID_Number and name for the five lowest paid employees.

This is the table with employees:

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

I will add that I've been trying a few methods and "limit" and "top" do not work for some reason.


回答1:


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

Prior to 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; 

queries may be used for Top-N Queries




回答2:


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



回答3:


The row_number() window function should work here (note that window functions can't be used in WHERE/HAVING clauses).

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



回答4:


In Oracle ROWNUM could be used.

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

Another method could be a subquery counting the rows with lower or equal salary.

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


来源:https://stackoverflow.com/questions/50519352/oracle-sql-finding-the-5-lowest-salaries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!