通过LINQ检索不活动的客户端

问题描述 投票:1回答:1

我的代码有问题。我想检索上周的所有非活动客户端(无订单)。这是我从数据库中获得的信息。information in database picture下面是我在LINQ中的代码,但不返回任何内容。

DateTime daysBeforeToday = DateTime.Today.AddDays(-7);
var queryCount = context.Orders.Select(x=>x.ID).Count();
var query = (from o in context.Orders
where o.OrderDate >= daysBeforeToday
select new { CustomerName = o.CustomerName, ID = o.ID } into Customers
group Customers by Customers.CustomerName into pg
where queryCount == 0
select pg.Key);
return query.ToList();

请咨询。谢谢

UPDATE我发现此SQL语句有效:

SELECT CustomerName, MAX(OrderDate) as LastOrderDate
FROM Orders 
GROUP By CustomerName
having MAX(OrderDate) < dateAdd(day,-7, GetDate())

但是当我在LINQ中转换时,它将失败。我做错了什么?

DateTime daysBeforeToday = DateTime.Today.AddDays(-7);
var queryMax = context.Orders.Select(x=>x.OrderDate).Max();

var query = (from o in context.Orders
            select new { CustomerName = o.CustomerName, Date = o.OrderDate } into Customers
            group Customers by Customers.CustomerName into pg
            where queryMax < daysBeforeToday
            select pg.Key);

return query.ToList();
database linq client orders
1个回答
0
投票

像评论一样,应该为每个分组的客户计算Max,如以下代码:

DateTime daysBeforeToday = DateTime.Today.AddDays(-7);

var query = (from o in context.Orders           
            group o by o.CustomerName into pg
            where pg.Max(x => x.OrderDate) < daysBeforeToday
            select pg.Key);

return query.ToList();

希望您能找到帮助。

© www.soinside.com 2019 - 2024. All rights reserved.