我正在尝试按星期几获取行实例的总平均数。因此,在过去一年中,我试图获得星期一/星期二/星期二/星期日发生的平均骑行数量。
这是我到目前为止所拥有的。这给了我每周一天的总数,但不是平均数。
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();
答案 0 :(得分:2)
如果我理解你,最后你会尝试获得一个号码,即每个工作日的平均数。这需要第二次分组,将数据减少到一个组:
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();
答案 1 :(得分:0)
这是有效的。谢谢@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()
答案 2 :(得分:-1)
不清楚你想要的属性的平均值,但假设你有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();