How to get second-highest salary employees in a table

后端 未结 30 1041
离开以前
离开以前 2020-12-23 20:15

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

30条回答
  •  情书的邮戳
    2020-12-23 21:10

    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;
    

提交回复
热议问题