Here we will present one possible answer to finding the nth highest
salary first, and the explanation of that answer after since it’s
actually easier to understand that way. Note that the first answer we
present is actually not optimal from a performance standpoint since it
uses a subquery, but we think that it will be interesting for you to
learn about because you might just learn something new about SQL. If
you want to see the more optimal solutions first, you can skip down to
the sections that says “Find the nth highest salary without a subquery”
instead.
The SQL below will give you the correct answer – but you will have to plug in an actual value for N of course. This SQL to find the Nth highest salary should work in SQL Server, MySQL, DB2, Oracle, Teradata, and almost any other RDBMS:
DECLARE @tbl table(sid int,mark int)
insert into @tbl values(1,234)
insert into @tbl values(2,134)
insert into @tbl values(3,334)
insert into @tbl values(1,534)
insert into @tbl values(2,634)
insert into @tbl values(3,634)
insert into @tbl values(10,834) -- ??
SELECT mark,max(mark) FROM @tbl group by mark order by mark desc--having max(mark)
SELECT * FROM @tbl WHERE mark=(SELECT top 1 mark FROM @tbl WHERE mark<>(SELECT top 1 mark FROM @tbl order by mark desc) ORDER BY mark desc)
SELECT * /*This is the outer query part */
FROM @tbl s1
WHERE (3-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(s2.mark))
FROM @tbl s2
WHERE s2.mark > s1.mark)
The SQL below will give you the correct answer – but you will have to plug in an actual value for N of course. This SQL to find the Nth highest salary should work in SQL Server, MySQL, DB2, Oracle, Teradata, and almost any other RDBMS:
SELECT * /*This is the outer query part */ FROM Employee Emp1 WHERE (N-1) = ( /* Subquery starts here */ SELECT COUNT(DISTINCT(Emp2.Salary)) FROM Employee Emp2 WHERE Emp2.Salary > Emp1.Salary)
DECLARE @tbl table(sid int,mark int)
insert into @tbl values(1,234)
insert into @tbl values(2,134)
insert into @tbl values(3,334)
insert into @tbl values(1,534)
insert into @tbl values(2,634)
insert into @tbl values(3,634)
insert into @tbl values(10,834) -- ??
SELECT mark,max(mark) FROM @tbl group by mark order by mark desc--having max(mark)
SELECT * FROM @tbl WHERE mark=(SELECT top 1 mark FROM @tbl WHERE mark<>(SELECT top 1 mark FROM @tbl order by mark desc) ORDER BY mark desc)
SELECT * /*This is the outer query part */
FROM @tbl s1
WHERE (3-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(s2.mark))
FROM @tbl s2
WHERE s2.mark > s1.mark)