How to get second-highest salary employees in a table

后端 未结 30 955
离开以前
离开以前 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 20:57
    SELECT * from Employee 
    WHERE Salary IN (SELECT MAX(Salary) 
                     FROM Employee 
                     WHERE Salary NOT IN (SELECT MAX(Salary) 
                                          FFROM employee));
    

    Try like this..

    0 讨论(0)
  • 2020-12-23 20:59

    Can we also use

    select e2.max(sal), e2.name
    from emp e2
    where (e2.sal <(Select max (Salary) from empo el))
    group by e2.name
    

    Please let me know what is wrong with this approach

    0 讨论(0)
  • 2020-12-23 20:59
    SELECT MAX(Salary) FROM Employee
    WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)
    
    0 讨论(0)
  • 2020-12-23 21:00

    How about a CTE?

    ;WITH Salaries AS
    (
        SELECT Name, Salary,
           DENSE_RANK() OVER(ORDER BY Salary DESC) AS 'SalaryRank'
        FROM 
            dbo.Employees
    )
    SELECT Name, Salary
    FROM Salaries  
    WHERE SalaryRank = 2
    

    DENSE_RANK() will give you all the employees who have the second highest salary - no matter how many employees have the (identical) highest salary.

    0 讨论(0)
  • 2020-12-23 21:02
    select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );
    
    0 讨论(0)
  • 2020-12-23 21:02
    SELECT name
    FROM employee
    WHERE salary =
    (SELECT MIN(salary) 
      FROM (SELECT TOP (2) salary
      FROM employee
      ORDER BY salary DESC) )
    
    0 讨论(0)
提交回复
热议问题