Second Highest Salary

后端 未结 10 1490
无人共我
无人共我 2020-12-20 06:14

Write a SQL query to get the second highest salary from the Employee table.

    | Id | Salary |
    | 1  | 100    |
    | 2  | 200    |
    | 3  | 300    |
<         


        
相关标签:
10条回答
  • 2020-12-20 07:04
    SELECT id, MAX(salary) AS salary 
    FROM employee 
    WHERE salary IN
    (SELECT salary FROM employee MINUS SELECT MAX(salary) 
    FROM employee); 
    

    You can try above code to find 2nd maximum salary. The above code uses MINUS operator. For further reference use the below links https://www.techonthenet.com/sql/minus.php https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/

    0 讨论(0)
  • 2020-12-20 07:05
    select case 
    when cnt>1 then SecondHighestSalary
    else null end as SecondHighestSalary
    from 
    (select top 1 Salary as SecondHighestSalary,
    (select count(distinct Salary)  from Employee) as cnt 
    from (
    select distinct top 2 Salary 
    from Employee
    order by Salary desc ) as sal
    order by SecondHighestSalary asc) as b
    
    0 讨论(0)
  • 2020-12-20 07:06

    you should be able to do that with OFFSET 1/FETCH 1:

    https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx

    0 讨论(0)
  • 2020-12-20 07:08

    Here is the easy way to do this

    SELECT MAX(Salary) FROM table WHERE Salary NOT IN (SELECT MAX(Salary) FROM table);
    
    0 讨论(0)
提交回复
热议问题