如何在Linq到Sql的子查询中选择MAX

时间:2011-07-13 15:37:05

标签: sql linq linq-to-sql

鉴于以下数据,如何使用LINQ仅为每个项目选择最新版本?

ItemId, Version
===================
A, 1
A, 2
A, 3
B, 8
B, 9,
C, 10
C, 11

期望的结果是:

A, 3
B, 9
C, 11

在TSQL中,我会这样做:

SELECT * FROM MyTable AS Tbl1

WHERE Tbl1.Version = 

(SELECT MAX(Version) 
FROM MyTable 
WHERE MyTable.ItemId = Tbl1.ItemId)

4 个答案:

答案 0 :(得分:3)

我会选择类似的东西:

MyTable
.GroupBy(row => row.ItemId)
.Select(grouping => 
    new
    {   
        ItemId = grouping.Key, 
        Version = grouping.Max(row => row.Version),
    });

编辑:修复了错误的SQL输出。

答案 1 :(得分:2)

        var data = new[] {
            new { item1 = "A", item2 = 1},
            new { item1 = "A", item2 = 2},
            new { item1 = "A", item2 = 3},
            new { item1 = "B", item2 = 8},
            new { item1 = "B", item2 = 9},
            new { item1 = "C", item2 = 10},
            new { item1 = "C", item2 = 11}
        };

        var res = data.GroupBy(el => el.item1).Select(gr => new { item1 = gr.Key, item2 = gr.Max(el => el.item2) });

        foreach (var el in res)
        {
            Console.WriteLine(el.item1 + ": " + el.item2);
        }

答案 2 :(得分:0)

select itemid, max(version)
from table
group by itemid

答案 3 :(得分:0)

如果您更喜欢查询语法:

from item in MyDBContext.MyTable
group item by item.ItemId into g
select new { ItemId = g.Key, Version = g.Max(x => x.Version) };