带有LINQ的max(date)的SQL

时间:2018-08-07 08:19:39

标签: sql linq

我试图在linq中创建以下sql,但没有运气可以帮助吗?

select * from customer c
where companynumber = 1 
      and status <> 0 
      and lastdate = (select max(lastdate) from customer where customernumber = c.customernumber)

给出22条记录

我最好的尝试是

_ctx.Customers
    .Where(r => r.CompanyNumber == companyNumber && r.CustomerNumber != null && r.Status != 0)
    .GroupBy(c => c.CustomerNumber)
    .Select(g => new
    {
        name = g.Key,
        count = g.Count(),
        date = g.Max(x => x.LastEdited)
    })
    .OrderBy(c => c.name);

提供22.000条以上记录

但不是上述SQL的结果

更新:

以下LINQ可以解决问题; o)

from a in _ctx.Customers
where a.CustomerNumber != null && a.CompanyNumber == companyNumber
group a by new { a.CustomerNumber } into g
select g.OrderByDescending(a => a.LastEdited).FirstOrDefault() into c
where c.Status == 1
select c

我必须将where c.Status == 1移到我的第一条选择声明中

0 个答案:

没有答案