Linq中的SQL:Group&每列的最大值

时间:2017-01-05 13:53:01

标签: c# sql entity-framework linq

我必须将这个SQL语句转换为Linq:

select id, workerId, max(timestamp) as Datex, clientId from order where clientId = '123' group by workerId;

它创建一个包含表顺序的每一列的表。但它只显示clientID = 123的行并按工作人员对其进行分组。它仅显示最新条目(最大时间戳)

如何将其转移到Linq?我尝试了一切。例如,这不起作用:

var selectedOrder = from s in order
                    where s.clientID == "123"
                    group s by s.workerId into g
                    select new {  id = s.id, workerId = g.Key, Datex = g.Max(s => s.timestamp), s.clientID};

更新:

  1. 我想举个例子:
  2. id: 1   workerId: 162   Datex: 2014-11-13   clientId: 123 
    id: 2   workerId: 162   Datex: 2016-01-07   clientId: 123 
    id: 3   workerId: 222   Datex: 2015-12-12   clientId: 123 
    id: 4   workerId: 222   Datex: 2013-01-22   clientId: 100 
    id: 2   workerId: 162   Datex: 2011-11-07   clientId: 123
    

    由于我想要的查询:

      id: 2   workerId: 162   Datex: 2016-01-07   clientId: 123 
      id: 3   workerId: 222   Datex: 2015-12-12   clientId: 123
    

    - >所以我的第一张桌子里只有两个不同的工人。我想显示每个工作人员的最新日期行

1 个答案:

答案 0 :(得分:1)

您可以使用OrderBy并使用First(),查询应该是

var selectedOrder = (from s in order
            where s.clientID == "123"
            select new
            {
                id = s.id,
                workerId = s.workerId,
                Datex = s.timestamp,
                clientID =s.clientID
            }).OrderBy(d => d.Datex).First();

GroupBy多列

var selectedOrder = from s in order
            where s.clientID == "123"
            group s by new {s.workerId, s.id, s.clientID}
            into g
            select
            new
            {
                id = g.Key.id,
                workerId = g.Key.workerId,
                Datex = g.Max(s => s.timestamp),
                clientID = g.Key.clientID
            };