Mostly people faced this question in interview find highest salary so I am just trying to explain different ways
let us understand this by following example
suppose we have following table of employees with salary
Query 1:- by aggregate function
SELECT MAX (fltBasicSalary)
FROM @tblEmployeeSalary
WHERE fltBasicSalary IN (SELECT DISTINCT TOP 2 fltBasicSalary
FROM @tblEmployeeSalary
ORDER BY fltBasicSalary ASC)
Query 2:- by Inline Query
SELECT MIN(fltBasicSalary)
FROM @tblEmployeeSalary e1
WHERE 2 <=(SELECT COUNT(*)
FROM @tblEmployeeSalary e2 WHERE e1.fltBasicSalary >= e2.fltBasicSalary);
Query 3:- BY Row_Number()
SELECT tmp.fltBasicSalary
FROM (SELECT DISTINCT fltBasicSalary ,
ROW_NUMBER()OVER (ORDER BY fltBasicSalary ASC) As intRowNumber
FROM @tblEmployeeSalary)tmp
WHERE tmp.intRowNumber = 2
Query 4:- BY Rank()
SELECT tmp.fltBasicSalary
FROM (SELECT DISTINCT fltBasicSalary ,
RANK()OVER (ORDER BY fltBasicSalary ASC) As intRowNumber
FROM @tblEmployeeSalary)tmp
WHERE tmp.intRowNumber = 2
Query 5:- Group by & Sub query
SELECT TOP 1 fltBasicSalary
FROM (SELECT TOP 2 fltBasicSalary
FROM @tblEmployeeSalary
GROUP BY fltBasicSalary ORDER BY fltBasicSalary ASC) AS tmp ORDER BY fltBasicSalary DESC
I hope you like it.
Enjoy !!!
RJ
Comments
Sandeep's making bank!
How about this : SELECT fltBasicSalary FROM tblEmployeeSalary ORDER BY fltBasicSalary DESC LIMIT 1
The Query 1 might be SELECT MIN (fltBasicSalary) instead of MAX if you want the second higher salary.
that's my answer,
i think it 's the clearer way of doing that
SELECT fltBasicSalary
FROM @tblEmployeeSalary
ORDER BY fltBasicSalary desc
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY