Tuesday 4 September 2018

LINQ Query to find nth Highest Salary

In this post, I will explain a LINQ Query to find nth Highest Salary. 

In below LINQ query subquery returns the count of distinct salary greater than current employee salary. Then the result of subquery will be compared with N and record with subquery result count equal N will be returned as result.

int N = 2;
var employees = db.Employees
               .Where(em1 =>
                        db.Employees.Select(em2 => new { em2.Salary })
                        .Where(em2 => em2.Salary > em1.Salary)
                        .Distinct().Count().Equals(N)
                       );

            GridView1.DataSource = employees;
            GridView1.DataBind();


Table Script-

CREATE TABLE Employee(
 EmployeeId int IDENTITY(1,1) ,
 EmployeeName varchar(100) NULL,
 Salary decimal(18, 2) NULL,

0 comments:

Post a Comment

Please do not enter any spam link in the message box.