How to get second-highest salary employees in a table

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

    Creating temporary table

    Create Table #Employee (Id int identity(1,1), Name varchar(500), Salary int)
    

    Insert data

    Insert Into #Employee
        Select 'Abul', 5000
    Union ALL 
        Select 'Babul', 6000
    Union ALL 
        Select 'Kabul', 7000
    Union ALL 
        Select 'Ibul', 8000
    Union ALL 
        Select 'Dabul', 9000
    

    Query will be

    select top 1 * from #Employee a
    Where a.id <> (Select top 1 b.id from #Employee b ORDER BY b.Salary desc)
    order by a.Salary desc
    

    Drop table

    drop table #Empoyee
    

提交回复
热议问题