Friday, October 29, 2021

Find Ist, 2nd and 3rd highest salary from table in MS SQL

 For example we have table with following entries:-


If we want to find the 1st highest salary:-

SELECT TOP 1 SALARY FROM (SELECT DISTINCT TOP 1 SALARY FROM EMP ORDER BY SALARY DESC) RESULT ORDER BY SALARY 

Result :- 5000

----------------------------------

If we want to find the 2nd highest salary:-

SELECT TOP 1 SALARY FROM (SELECT DISTINCT TOP 2 SALARY FROM EMP ORDER BY SALARY DESC) RESULT ORDER BY SALARY 

Result :- 3000

---------------------------------------

If we want to find the 3rd highest salary:-

SELECT TOP 1 SALARY FROM (SELECT DISTINCT TOP 3 SALARY FROM EMP ORDER BY SALARY DESC) RESULT ORDER BY SALARY 

Result :- 1000

No comments:

Post a Comment