林克每周的平均计数

本文关键字:每周 林克 | 更新日期: 2023-09-27 18:27:59

我正在尝试按一周中的某一天获取行实例的总平均计数。因此,在过去的一年里,我试图获得周一/周二/周三/周五的平均乘车次数。

这是我迄今为止所拥有的。这给了我一周中每天的总计数,但不是平均计数。

UnitOfWork.Query<WorkoutRecord>()
   .Where(x => x.WorkoutDate > baseDate)
   .GroupBy(x => SqlFunctions.DatePart("weekday", x.UploadDate))
   .Select(x => new AdminDashboardWorkoutsGroupedDay()
   {
       DayOfWeek = (DayOfWeek)x.Key,
       WorkoutCount = x.Count()
   }).ToList();

林克每周的平均计数

如果我很理解你,最后你会试图得到一个数字,即每个工作日的平均计数。这需要第二个分组,将数据减少为一组:

UnitOfWork.Query<WorkoutRecord>()
   .Where(x => x.WorkoutDate > baseDate)
   .GroupBy(x => SqlFunctions.DatePart("weekday", x.UploadDate))
   .Select(x => new AdminDashboardWorkoutsGroupedDay()
   {
       DayOfWeek = (DayOfWeek)x.Key,
       WorkoutCount = x.Count()
   })
   .GroupBy(g => 0) // or g => "x", or whatever
   .Select (g1 => (decimal)g1.Sum(x => x.WorkoutCount) / g1.Count())
   .ToList();

以下是工作原理。谢谢@Gert Arnold,你让我非常接近。我必须按天分组,计算所有的锻炼,然后按工作日取分组的平均值。

UnitOfWork.Query<WorkoutRecord>()
    .Where(x => x.WorkoutDate > baseDate && x.TotalTicks > 600)
    .GroupBy(x => EntityFunctions.TruncateTime(x.UploadDate))
    .Select(x => new 
    {
        Date = x.Key ?? DateTime.UtcNow,
        TheCount = x.Count()
    })
    .GroupBy(x=> SqlFunctions.DatePart("weekday", x.Date))
    .Select (x => new AdminDashboardWorkoutsGroupedDay()
    {
        WorkoutCount = (x.Average(y=>y.TheCount)),
        DayOfWeek = (DayOfWeek)x.Key
    })
    .ToList()

目前还不清楚你想要什么属性的平均值,但假设你有一个像WorkoutRecord.Duration这样的属性,你应该能够得到平均值,比如:

UnitOfWork.Query<WorkoutRecord>()
    .Where(x => x.WorkoutDate > baseDate)
    .GroupBy(x => SqlFunctions.DatePart("weekday", x.UploadDate))
    .Select(x => new AdminDashboardWorkoutsGroupedDay()
    {
        DayOfWeek = (DayOfWeek)x.Key,
        AverageDuration = x.Average(w => w.Duration)
    })
    .ToList();