How to find third or nth maximum salary from salary table(EmpID, EmpName, EmpSalary)
in optimized way?
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With