C# 使用linq和EF6 C获得平均值#
我使用的是EF6,我有一个EmployeeAttention表,我想用Linq得到这个表中每个员工的平均总工作时间 日期|入住|结帐|员工ID 16/9/2018 | 09:40 | 16:26 | 2 17/9/2018 | 09:25 | 16:31 | 2 18/9/2018 | 09:46 | 16:18 | 2C# 使用linq和EF6 C获得平均值#,c#,entity-framework,linq,C#,Entity Framework,Linq,我使用的是EF6,我有一个EmployeeAttention表,我想用Linq得到这个表中每个员工的平均总工作时间 日期|入住|结帐|员工ID 16/9/2018 | 09:40 | 16:26 | 2 17/9/2018 | 09:25 | 16:31 | 2 18/9/2018 | 09:46 | 16:18 | 2 2018年9月19日| 10:14 | 16:18 | 2因此具有某个Id的员工有一系列员工出勤,其中每个员工出勤都有一个Employ
2018年9月19日| 10:14 | 16:18 | 2因此具有某个
Id
的员工有一系列员工出勤
,其中每个员工出勤
都有一个EmployeeId
值,该值等于员工所属的Id
每个员工考勤
都有一个签入时间和一个签出时间。你忘了告诉我们它的类型,所以我假设它类似于DateTime.TimeOfDay
。重要的是,您可以减去其中两次,从而得到TimeSpan
让我们将签入和签出之间的时间跨度定义为Shift
您可能会遇到一些未指定的问题:
- 您指定一名
员工
一天可以有多个签入
和签出
。这些时间可以重叠吗
- 如果一名
员工
在某一天报到,第二天报到怎么办
- 如果
员工
登记入住,但根本不结账怎么办
- 如果员工在某一天没有签入/签出,该怎么办?这算不算平均数,还是不算平均数
所以让我们假设班次不重叠,在午夜前结束,如果员工根本不工作,不会影响平均值
让我们将每个员工的出勤率分组,然后是每天的出勤率,并将当天的所有班次相加。结果:每个雇员,每个日期,你有他当天工作的总时间
var WorkingTimePerDatePerEmployee = myDbContext.Attendencies
// make groups of attendencies for the same Employee
.GroupBy(attendancy => employee.Id,
// the attendancies in the group are all for the same Employee
(employeeId, attendanciesForThisEmployeeId) => new
{
EmployeeId = employeeId,
AttendanciesGroupedByDate = attendanciesForThisEmployeeId
// group by same Date:
.GroupBy(attendancy2 => attendancy2.Date,
(date, sameDateAttendancies => new
{
Date = date
TotalWorkingHoursOnDate = sameDateAttendancies
// per attendancy select CheckOut - CheckIn = working time per shift
.Select(sameDateAttendancy => sameDateAttendancy.Checkout - sameDateAttendancy.Checkin)
// sum all shifts on this date
.Sum(),
}),
});
现在你有了每个雇员ID,他工作的所有日期。您只需将所有班次相加,然后除以工作天数。请定义平均值。平均每天?平均每个条目?日期是唯一的吗?MVC与这个问题完全无关——生成的LINQ查询是一个浮点数或双精度查询,然后如何处理它不是问题的一部分。每个条目的平均值,日期不唯一,结果将是浮点数。我想您的类型在SQL端是什么样的?我假设雇员的ID是整数?日期是SQLDate
还是SQLDateTime
?签入和签出情况如何?从2018年9月16日到2018年9月19日的每个日期的平均值,日期不唯一,结果将是浮点数ithink@Flydog57Employee_ID是整数日期是字符串,签入和签出是Sting