Saleem
Saleem

Reputation: 730

LINQ query to select records from table where 2 columns have max values

I have the following data in sql server table:

EmployeeId  ForMonth    ForYear     Value   
1           1           2015        45000.00
1           6           2015        35000.00
1           12          2014        66666.00
2           1           2015        70000.00
2           5           2015        80000.00

I need to find the LINQ-to-SQL query to select for each EmployeeId the record having max ForMonth and max ForYear. So the result should be:

EmployeeId  ForMonth    ForYear     Value   
1           6           2015        35000.00
2           5           2015        80000.00

It's not that I didn't try to solve this before coming and posting this question, but the problem is that I didn't know how to write this query in SQL server, so I don't have any LINQ code to add. Please if you find this a bad question, ask me to delete it.

Upvotes: 1

Views: 1200

Answers (2)

Aducci
Aducci

Reputation: 26644

You only want 1 record per employee, so you need to group by the ID. Then you order your groups by the lastest year/month and select the first one

var query = from e in db.Employees
            group e by e.EmployeeId into g
            select g.OrderByDescending(e => e.ForYear)
                    .ThenByDescending(e => e.ForMonth)
                    .FirstOrDefault();

Upvotes: 2

laskdjf
laskdjf

Reputation: 1183

I am assuming you want the record with the greatest ForYear and greatest ForMonth

var result = (from db in MYDBContext
             orderby db.ForYear descending, db.ForMonth descending
             select db).First();

Upvotes: 0

Related Questions