【问题标题】:How to write this in Linq? group and get max如何在 Linq 中写这个?分组并获得最大值
【发布时间】:2013-10-11 07:17:59
【问题描述】:
select * 
from monthStatistics ms 
    where ms.beloneMonth = 
         (
            select max(ms2.beloneMonth) 
            from monthStatistics ms2 
            where ms.materialDictionaryId = ms2.materialDictionaryId 
            and ms.locationId = ms2.locationId 
            and ms.price=ms2.price
          )

样本数据

id  beloneMonth       materialDictinaryId    price  acount
1   2013/7            1                      100    200
2   2013/7            2                      100    200
3   2013/8            1                      100    200
4   2013/8            1                      200    200

结果:

id  beloneMonth       materialDictinaryId    price  acount
2   2013/7            2                      100    200
3   2013/8            1                      100    200
4   2013/8            1                      200    200

分组并获取最大月份行。

【问题讨论】:

  • 你给出的 SQL 并没有真正显示你想要做什么。我们需要先修复您的 SQL,然后我们需要转换为 Linq。
  • 您可以查看我的编辑。您需要的是 Group By id,然后为每个 id 获取最大 beloneMonth 的行。

标签: linq group-by max


【解决方案1】:

以下将返回monthStatistics 的行,该行在beloneMonth 中具有max

monthStatistics
    .GroupBy(x=>x.id)
    .SelectMany
    (
        x=>
        x.Where
        (
            z=>
            z.beloneMonth == x.Max(y=>y.beloneMonth)
        )
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2011-01-03
    • 2015-03-15
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多