Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find 2nd max salary using linq

Tags:

c#

linq

I have following sql query for finding 2nd max salary.


Select * From Employee E1 Where
    (2) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where
        E2.Salary > E1.Salary)

I want to convert it into Linq statement.

like image 205
santosh singh Avatar asked Dec 15 '10 11:12

santosh singh


People also ask

How do you find the 2nd highest salary?

SELECT MAX(SALARY) FROM Employee WHERE SALARY < (SELECT MAX(SALARY) FROM Employee); This query will give you the desired output i.e 12000, which is the second highest salary.

How do you find the nth highest salary in Linq?

Linq Query: var result = employees. OrderByDescending(x => x. Salary).


1 Answers

I think what you're asking is to find the employee with the second-highest salary?

If so, that would be something like

var employee = Employees
    .OrderByDescending(e => e.Salary)
    .Skip(1)
    .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();

(kudos to @diceguyd30 for suggesting this latter enhancement)

like image 97
Ian Nelson Avatar answered Sep 20 '22 11:09

Ian Nelson