We can find the nth salary by using CTE also as follows.
EMPLOYEE TABLE
select salary, DENSE_RANK( ) over (order by salary desc) as densrank
from employee
select salary, DENSE_RANK( ) over (order by salary desc) as densrank
from employee
select top 1 salary
from result where result.densrank=N
select salary, DENSE_RANK( ) over (order by salary desc) as densrank
from employee
select top 1 salary
from result where result.densrank=2
with result as
select salary, ROW_NUMBER( ) over (order by salary desc) as rownumber
from employee
select salary from result where rownumber=N
EMPLOYEE TABLE
Name | Salary |
---|---|
1000 | |
2000 | |
3000 | |
4000 |
Here we are used DENSE_RANK( )
Salary | |
---|---|
4000 | 1 |
3000 | 2 |
2000 | 3 |
1000 | 4 |
The following is the query by using CTE
WITH Result
AS
(
)
If you want to find second highest salary, then following is a query where we need to replace 2 instead of N.
WITH Result
AS
(
)
Now the result is 3000.
Some of the blogs will use ROW_NUMBER( ), but it works only if you do not have duplicates otherwise result might be wrong. The following is the query.
(
)
No comments:
Post a Comment