How to get second-highest salary employees in a table

后端 未结 30 954
离开以前
离开以前 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:04

    Try This one

        select * from
       (
        select name,salary,ROW_NUMBER() over( order by Salary desc) as
        rownum from    employee
       ) as t where t.rownum=2
    

    http://askme.indianyouth.info/details/write-a-sql-query-to-find-the-10th-highest-employee-salary-from-an-employee-table-explain-your-answer-111

    0 讨论(0)
  • 2020-12-23 21:04

    I want to post here possibly easiest solution. It worked in mysql.

    Please check at your end too:

    SELECT name
    FROM `emp`
    WHERE salary = (
    SELECT salary
    FROM emp e
    ORDER BY salary DESC
    LIMIT 1
    OFFSET 1 
    
    0 讨论(0)
  • 2020-12-23 21:07

    Select * from employee where salary = (Select max(salary) from employee where salary not in(Select max(salary)from employee))

    Explanation :

    • Query 1 : Select max(salary) from employee where salary not in(Select max(salary) from employee) - This query will retrieve second highest salary

    • Query 2 : Select * from employee where salary=(Query 1) - This query will retrieve all the records having second highest salary(Second highest salary may have multiple records)

    0 讨论(0)
  • 2020-12-23 21:08
    select * from emp where salary = (  
        select salary from   
           (select ROW_NUMBER() over (order by salary) as 'rownum', *
            from emp) t -- Order employees according to salary  
        where rownum = 2 -- Get the second highest salary
    )
    
    0 讨论(0)
  • 2020-12-23 21:09

    Here's a simple approach:

    select name
    from employee
    where salary=(select max(salary)
                  from(select salary from employee
                       minus
                       select max(salary) from employee));
    
    0 讨论(0)
  • 2020-12-23 21:10

    Another intuitive way is :- Suppose we want to find Nth highest salary then

    1) Sort Employee as per descending order of salary

    2) Take first N records using rownum. So in this step Nth record here is Nth highest salary

    3) Now sort this temporary result in ascending order. Thus Nth highest salary is now first record

    4) Get first record from this temporary result.

    It will be Nth highest salary.

    select * from 
     (select * from 
       (select * from  
           (select * from emp order by sal desc)  
       where rownum<=:N )  
     order by sal )
    where rownum=1;
    

    In case there are repeating salaries then in innermost query distinct can be used.

    select * from 
     (select * from 
       (select * from  
           (select distinct(sal) from emp order by 1 desc)  
       where rownum<=:N )  
     order by sal )
    where rownum=1;
    
    0 讨论(0)
提交回复
热议问题