views:

57

answers:

5

I have a table called Employee with the following fields:

  • EmpID
  • Salary
  • Name

I want to get top two employees with maximum salary. How do I write this query ?

+1  A: 

Try this ..

SELECT * from Employee  order by Salary  desc limit 2 ;
pavun_cool
Or, if using SqlServer, _select top 2 * from employees order by salary_.
Michael Todd
+1  A: 

SELECT TOP 2 * FROM Employee ORDER BY Salary DESC;

uvita
+3  A: 

SQL Server 2000+:

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

MySQL & 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
OMG Ponies
+1  A: 

You should write something like this.

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

Wonde
A: 

Yet another solution:

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
Thomas
`ROW_NUMBER()` (CTE too) is SQL Server 2005+
OMG Ponies
Although technically the OP did not specify the version of SQL. Technically, it could have been SQL Server 4.2 in which the TOP command would not exist. ;)
Thomas