Wednesday 2 August 2017

Find 2nd highest salary using sql and LINQ


Find 2nd highest salary using sql
Select TOP 1 Salary
from (SELECT DISTINCT TOP 2 Salary from Employee ORDER BY Salary ASC)
a ORDER BY Salary DESC

Find 2nd highest salary using LINQ

var employee = Employees
                         .OrderByDescending(e => e.Salary)
                         .Skip(1)  //skip(N-1) N is 2
                         .First();

If multiple employees may have equal salary and you wish to return an IEnumerable of all the employees with the second-highest salary you could do

var employees = Employees
                           .GroupBy(e => e.Salary)
                          .OrderByDescending(g => g.Key)
                          .Skip(1)
                           .First();

No comments:

Post a Comment