我有这个结果集:
Company_ID | State | City | Rev |
Company 1 | S-A | C-1 | 1 |
Company 2 | S-B | C-2 | 1 |
Company 1 | S-A | C-3 | 2 |
我想要的结果集是
Company_ID | State | City | Rev |
Company 1 | S-A | C-3 | 2 |
Company 2 | S-B | C-2 | 1 |
以下是我尝试的查询:
var list = (from coy in TBL_COMPANY
where coy.IsActive == "1"
select coy).ToList()
.Select(coy => new
{
coy.Company_ID,
coy.State,
coy.City,
coy.Rev
});
var companyList = list.GroupBy (grp => new
{
grp.Company_ID,
grp.State,
grp.City
})
.Select(cpy => new
{
CompanyID = cpy.Key.Company_ID,
State = cpy.Key.State,
City = cpy.Key.City,
Rev = cpy.Max(c => c.Rev)
}).ToList();
但是,我无法获得我想要的结果集。我怀疑是因为City
因为它被包括在内。但是,我需要这些列(Rev
除外)。有没有办法做到这一点?
答案 0 :(得分:2)
所需的结果并不适合您的分组。有3个不同的City
项目应该会产生3个结果项目。
我说Jon Skeet关于Company_ID
分组 的评论是正确的。
代码(按Company_ID
分组并选择Rev
项最高的项目:
var result = TBL_COMPANY.Where(x => x.IsActive == "1")
.GroupBy(x => x.Company_ID)
.Select(x => x.OrderByDescending(y => y.Rev).First())
.Select(x=> new {x.Company_ID, x.State, x.City, x.Rev})
.ToList();