LINQ to Entities从有序分组中找到最高记录

时间:2011-07-04 23:18:03

标签: c# sql wcf

我遇到一个问题,我知道如何在SQL中解决,但不能使用Linq to Entities。

我的数据如下:

ID    GROUP   TIMESTAMP
--    -----   ---------
1     A       2011-06-20
2     A       2011-06-21
3     B       2011-06-21
4     B       2011-06-22
5     B       2011-06-23
6     C       2011-06-30

我想检索所有Entity对象(而不仅仅是ID),这样我才能从每个组中获取最新记录。 (即带有ids 2,5,6的记录)

在SQL中我会做这样的事情:

SELECT * FROM my_table a
WHERE a.timestamp = 
   (SELECT MAX(timestamp) FROM my_table b
   WHERE a.group = b.group)

(为了这个问题,您可以假设时间戳在每个组中都是唯一的。)

我想使用Linq to Entities对WCF数据服务进行此查询,但我似乎没有像这样引用外部查询的嵌套查询。有人可以帮忙吗?

4 个答案:

答案 0 :(得分:2)

可能没有手写版本那么干净和高效,但这就是我想出来的

    var q = from a in db.MyEntities
            where a.Timestamp == (from b in db.MyEntities
                                  where b.Group == a.Group
                                  select b.Timestamp).Max()
            select a;

转换为此SQL

SELECT
[Project1].[Id] AS [Id],
[Project1].[Group] AS [Group],
[Project1].[Timestamp] AS [Timestamp]
FROM ( SELECT
        [Extent1].[Id] AS [Id],
        [Extent1].[Group] AS [Group],
        [Extent1].[Timestamp] AS [Timestamp],
        [SSQTAB1].[A1] AS [C1]
        FROM [MyEntities] AS [Extent1]
         OUTER APPLY
        (SELECT
                MAX([Extent2].[Timestamp]) AS [A1]
                FROM [MyEntities] AS [Extent2]
                WHERE [Extent2].[Group] = [Extent1].[Group]) AS [SSQTAB1]
)  AS [Project1]
WHERE [Project1].[Timestamp] = [Project1].[C1]

答案 1 :(得分:1)

您好尝试使用linqer将您的sql语句转换为linq查询。

Linqer

最好的问候

答案 2 :(得分:0)

这应该有效:

var query = db.my_table
   .GroupBy(p=>p.group)
   .Select(p=>p.OrderByDescending(q=>q.timestamp).First());

答案 3 :(得分:0)

你走了。一个简单的方法。

      var result = (from x in my_table
                      group x by x.Group into g
                      select new
                      {
                          g.Key,
                          timestamp = g.Max(x => x.TimeStamp),
                          g //This will return everything in g
                      });