简体   繁体   中英

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.

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM