不简单的麦克斯

Not a simple Max

我有以下数据:

Id     | Value | OtherStuff
---------------------------
6      | 6     | 1
---------------------------
5      | 4     | 2
---------------------------
5      | 2     | 3

想要的结果:

Id     | Value | OtherStuff
---------------------------
6      | 6     | 1
---------------------------
5      | 4     | 2

也就是说,我需要每个 ID 的最大值。

我有点困惑如何在不将其分解为多个查询的情况下执行此操作,是否可以完成,如果可以,怎么做?

更新:我想我把问题简单化了:

var query = from st in StockStakes
            join o in Organisations on j.OrganisationId equals o.OrganisationId into oGroup
            from o in oGroup.DefaultIfEmpty()
            where st.Stock.Status == "A"
            select new
            {
                Id = st.Id,
                Value = st.Value,
                CustomerId = o.OrganisationId
            };

上面的数据样本仍然有效...现在我该如何构造查询以在每个 ID 旁边给我最大值?

我不太确定你的意思,但也许你可以试试这个查询。

select Id, max(Value)
from your_table
group by Id;

这为您提供每个 "Id column" 值的最大 "Value column" 值。

-- 编辑 --

LINQ 版本:

var q = from t in dc.YourTable
    group t by t.Id
    into g
    select new
    {
        Id = g.Id,
        Value = (from t2 in g select t2.Value).Max()
    };

代码未经测试。我现在在公共汽车上...:-) 试试吧!

var query = from x in data
            group x by x.Id into x
            select x.OrderByDescending(y => y.Value).FirstOrDefault()

根据您更新的查询,与第一个查询类似的方法,但由于您有多个表,您需要将所有表分组到一个匿名对象中,然后 select 只包含您想要的列

var query = from st in StockStakes
            join o in Organisations on j.OrganisationId equals o.OrganisationId into oGroup
            from o in oGroup.DefaultIfEmpty()
            where st.Stock.Status == "A"
            group new { st, o } by st.Id into g
            let largestValue = g.OrderByDescending(x => x.Value).FirstOrDefault()
            select new
            {
                Id = g.Key,
                Value = largestValue.st.Value,
                CustomerId = largestValue.o.OrganisationId
            };