How to get second-highest salary employees in a table

后端 未结 30 956
离开以前
离开以前 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
    SELECT * 
    FROM TABLE1 AS A 
    WHERE NTH HIGHEST NO.(SELECT COUNT(ATTRIBUTE) FROM TABLE1 AS B) WHERE B.ATTRIBUTE=A.ATTRIBUTE;
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-23 21:11
     - 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 )
    
    0 讨论(0)
  • 2020-12-23 21:12

    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);
    
    0 讨论(0)
  • 2020-12-23 21:13

    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)
    
    0 讨论(0)
  • 2020-12-23 21:13

    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.

    0 讨论(0)
提交回复
热议问题