我正在从数据库中获取产品列表,每个产品都填充了paymentDate,我想这样格式化我的数据(仅作为示例):
{
Week:1,
Month:8,
Total:50
},
{
Week:2,
Month:8,
Total:40
},
{
Week:3,
Month:8,
Total:70
},
{
Week:4,
Month:8,
Total:85
}
... and so on..
现在,我按月对数据进行分组,并在 4 个月内返回4 INSTEAD OF 16 行,例如:
Month:8,
Total:250
那就是我所不想要的。
这是我的代码:
首先,我要从数据库中获取最近4个月的所有行,其中有20-30行的值为PaymentDate
(最近4个月的行)。
var yas = await _context.products
.AsNoTracking()
.Where(x => (x.PaymentDate != null && x.PaymentDate > DateTime.UtcNow.AddMonths(-4))).ToListAsync();
获取所有行之后,我试图将它们分组,以获取每个MONTE中按WEEKS分组的数据。
var grouped = yas.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.PaymentDate ?? DateTime.UtcNow, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select(product => new ProductsDemoData
{
//Week = should be week
Amount = product.Sum(x => x.Amount),
Month = product.FirstOrDefault().PaymentDate.Value.Month
});
数据示例:
答案 0 :(得分:1)
您已经按周分组,所以我认为您可以这样做:
.Select(product => new ProductsDemoData
{
Week = product.Key,
Amount = product.Sum(x => x.Amount),
Month = product.FirstOrDefault().PaymentDate.Value.Month
});