Query to retrieve the top two rows from a table in SQL Server

I have a table called Employeewith the following fields:

  • EmpID
  • Income
  • Name

I want to get the two best employees with the maximum salary. How to write this request?

+3
source share
5 answers

SQL Server 2000 +:

  SELECT TOP 2
         e.*
    FROM EMPLOYEE e
ORDER BY e.salary DESC

MySQL and Postgres:

  SELECT e.*
    FROM EMPLOYEE e
ORDER BY e.salary DESC
   LIMIT 2

Oracle:

SELECT x.*
  FROM (SELECT e.*,
               ROWNUM as rn
          FROM EMPLOYEE e
      ORDER BY e.salary DESC) x
 WHERE x.rn <= 2
+4
source

Try it.

SELECT * from Employee  order by Salary  desc limit 2 ;
+1
source

2 * DESC;

0

- .

SELECT TOP 2 EmpID, Salary, Name FROM Employee ORDER BY Salary

0

:

With NumberedItems As
    (
    Select EmpId, Salary, Name
        , Row_Number() Over ( Order By Salary Desc ) As SalaryRank 
    From Employee
    )
Select EmpId, Salary, Name
From NumberedItems
Where SalaryRank <= 2
0

Source: https://habr.com/ru/post/1736940/


All Articles