Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find third or nᵗʰ maximum salary from salary table?

How to find third or nth maximum salary from salary table(EmpID, EmpName, EmpSalary) in optimized way?

like image 793
Karan Gandhi Avatar asked Apr 26 '13 11:04

Karan Gandhi


People also ask

How can we find 3rd highest salary from table?

Here is a way to do this task using dense_rank() function. Query : select * from( select ename, sal, dense_rank() over(order by sal desc)r from Employee) where r=&n; To find to the 2nd highest sal set n = 2 To find 3rd highest sal set n = 3 and so on.

How do you find the maximum salary from a table?

Try using this SQL SELECT statement: SELECT * FROM employees WHERE department_id=30 AND salary = (SELECT MAX(salary) FROM employees WHERE department_id=30); This will return the employee information for only the employee in department 30 that has the highest salary.


2 Answers

Row Number :

SELECT Salary,EmpName FROM   (    SELECT Salary,EmpName,ROW_NUMBER() OVER(ORDER BY Salary) As RowNum    FROM EMPLOYEE    ) As A WHERE A.RowNum IN (2,3) 

Sub Query :

SELECT * FROM Employee Emp1 WHERE (N-1) = (                SELECT COUNT(DISTINCT(Emp2.Salary))                FROM Employee Emp2                WHERE Emp2.Salary > Emp1.Salary                ) 

Top Keyword :

SELECT TOP 1 salary FROM (       SELECT DISTINCT TOP n salary       FROM employee       ORDER BY salary DESC       ) a ORDER BY salary 
like image 142
Kumar Manish Avatar answered Sep 28 '22 11:09

Kumar Manish


Use ROW_NUMBER(if you want a single) or DENSE_RANK(for all related rows):

WITH CTE AS (     SELECT EmpID, EmpName, EmpSalary,            RN = ROW_NUMBER() OVER (ORDER BY EmpSalary DESC)     FROM dbo.Salary ) SELECT EmpID, EmpName, EmpSalary FROM CTE WHERE RN = @NthRow 
like image 20
Tim Schmelter Avatar answered Sep 28 '22 11:09

Tim Schmelter