How to find third or nth
maximum salary from salary table(EmpID,EmpName,EmpSalary)
in Optimized way?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
Use
ROW_NUMBER
(if you want a single) orDENSE_RANK
(for all related rows):This is one of the popular question in any SQL interview. I am going to write down different queries to find out the nth highest value of a column.
I have created a table named “Emloyee” by running the below script.
Now I am going to insert 8 rows into this table by running below insert statement.
Now we will find out 3rd highest Basic_sal from the above table using different queries. I have run the below query in management studio and below is the result.
We can see in the above image that 3rd highest Basic Salary would be 8500. I am writing 3 different ways of doing the same. By running all three mentioned below queries we will get same result i.e. 8500.
First Way: - Using row number function
MySQL tested solution, assume N = 4:
Another example:
//you can find n' th salary from table.if you want to retrive 2nd highest salary then put n=2,if 3rd hs then out n=3 as so on..
In 2008 we can use ROW_NUMBER() OVER (ORDER BY EmpSalary DESC) to get a rank without ties that we can use.
For example we can get the 8th highest this way, or change @N to something else or use it as a parameter in a function if you like.
In SQL Server 2012 as you might know this is performed more intuitively using LAG().