gpt4 book ai didi

c# - 根据子句加入并仅选择第一项

转载 作者:行者123 更新时间:2023-11-30 21:30:34 25 4
gpt4 key购买 nike

我有一个客户和一个订单数据库。我需要对所有新客户的首单进行一些统计,并按月统计新客户的首单数量。`

var date = new DateTime(now.Year - 1, now.Month, 1);
db.Orders
.Where(o => o.Customer.IsNew && o.OrderDate > date)
.GroupBy(o => new { o.OrderDate.Year, o.OrderDate.Month })
.Select(g => new NewCustomerStatsModel {
Month = g.Key.Month,
Year = g.Key.Year,
Count = g.Count()
})
.OrderBy(cs => cs.Year)
.ThenBy(cs => cs.Month)
.ToList();

此查询为我提供了所有新客户的订单数量,但如果第一个订单日期大于提供的日期,我只需要获取每个新客户的第一个订单的总和。

是否可以通过查询(以及如何)来完成,或者我是否被迫使用 AsEnumerable 并在内存中完成?

最佳答案

I need to make some statistics for the first order of all new customers

var clientFirstOrders = db.Customers.Where(c => c.IsNew)
.Select(c => new{
Customer = c,
FirstOrder = c.Orders.OrderBy(c => c.OrderDate).FirstOrDefault()
})
// might have to do (int?)FirstOrder.Id != null or something like that.
.Where(e => e.FirstOrder != null);

and count the number of first orders from new clients by month.

var clientCountByFirstOrderMonth = clientFirstOrders 
.GroupBy(e => new { e.FirstOrder.OrderDate.Year, e.FirstOrder.OrderDate.Month })
.Select(g => new{g.Key.Year, g.Key.Month, Count = g.Count()});

关于c# - 根据子句加入并仅选择第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54150627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com