LINQ 查询 select 来自 table 的记录,其中 2 列具有最大值

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

我在 sql 服务器 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

我需要为每个 EmployeeId 找到 LINQ-to-SQL 查询 select,该记录具有最大 ForMonth 和最大 ForYear。 所以结果应该是:

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

不是我来之前没有尝试解决这个问题,而是问题是我不知道如何在 SQL 服务器上写这个查询,所以我不知道无需添加任何 LINQ 代码。 如果你觉得这是一个不好的问题,请让我删除它。

我假设您想要最大 ForYear 和最大 ForMonth

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

每个员工只需要 1 条记录,因此需要按 ID 分组。然后你按最新的 year/month 和 select 第一个

排序你的组
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();