It\'s a question I got this afternoon:
There a table contains ID, Name, and Salary of Employees, get names of the second-highest salary employees, in SQL Server
SELECT *
FROM TABLE1 AS A
WHERE NTH HIGHEST NO.(SELECT COUNT(ATTRIBUTE) FROM TABLE1 AS B) WHERE B.ATTRIBUTE=A.ATTRIBUTE;
Here I used two queries for the following scenarios which are asked during an interview
First scenario:
Find all second highest salary in the table (Second highest salary with more than
one employee )
select * from emp where salary
In (select MAX(salary) from emp where salary NOT IN (Select MAX(salary) from
emp));
Second scenario:
Find only the second highest salary in the table
select min(temp.salary) from (select * from emp order by salary desc limit 2)
temp;
- Method 1
select max(salary) from Employees
where salary< (select max(salary) from Employees)
- Method 2
select MAX(salary) from Employees
where salary not in(select MAX(salary) from Employees)
- Method 3
select MAX(salary) from Employees
where salary!= (select MAX(salary) from Employees )
If you want to display the name of the employee who is getting the second highest salary then use this:
SELECT employee_name
FROM employee
WHERE salary = (SELECT max(salary)
FROM employee
WHERE salary < (SELECT max(salary)
FROM employee);
Below query can be used to find the nth maximum value, just replace 2 from nth number
select * from emp e1 where 2 =(select count(distinct(salary)) from emp e2
where e2.emp >= e1.emp)
There are two way to do this first:
Use subquery to find the 2nd highest
SELECT MAX(salary) FROM employees
WHERE salary NOT IN (
SELECT MAX (salary) FROM employees)
But this solution is not much good as if you need to find out the 10 or 100th highest then you may be in trouble. So instead go for window function like
select * from
(
select salary,ROW_NUMBER() over(
order by Salary desc) as
rownum from employees
) as t where t.rownum=2
By using this method you can find out nth highest salary without any trouble.