假設我有兩張桌子:
- 員工表:包含 EmployeeId、DepartmentId 等欄位...
- Signings/Attendance 表:包含 SigningId、Time、EmployeeId、SignType(in 或 out)等欄位...
我正在嘗試從某個日期時間(通常是 DateTime.Now)中屬于某個部門的每個員工中選擇最后一個簽名,因為我正在為我的公司開發一個基于考勤的應用程式。
到目前為止,我有以下查詢,它為滿足先前條件(部門和時間)的所有員工回傳 EmployeeId 和 SignType。我知道這個查詢應該有一個額外的連接(確切地說是左連接可能要感謝我昨天找到的這篇文章),但我真的不知道如何繼續,因為這是我第一次做如此復雜的 linq 查詢。
提前非常感謝。
from e in AppDbContext.Employees
join s in AppDbContext.Signings
on e.EmployeeId equals s.EmployeeId
where e.DepartmentId == DepartmentId
&& s.Time.Date == DateTime.Now.Date
select new Aux2()
{
Id = e.EmployeeId,
Type = s.SignType,
};
編輯:子查詢嘗試
AppDbContext.Employees
.Where(e => e.DepartmentId == DepartmentId )
.Select(e => new Aux2(){
Id = e.EmployeeId,
Type = AppDbContext.Signings
.Where(s => s.EmployeeId== e.EmployeeId && s.Time.Date==Date)
.OrderByDescending(s => s.Time)
.Take(1)
.Select(s => s.SigType)
.FirstOrDefault()
})
EDIT2:以前的非翻譯版本
List<Guid> treballadorsDepartament = MetodesComuns.GetTreballadorsDepartament(IdDepartament.Value, AppDbContext);
IQueryable<Fitxatge2> QueryFitxatge = AppDbContext.Fitxatges2
.Where(f => f.HoraAjustada.Date == Ara.Date && f.FKTreballador.IdDepartament == IdDepartament)
.AsNoTracking();
actives
IQueryable<Solicitut> QuerySollicitud = AppDbContext.Solicituts
.Where(s => (s.EstatSolicitut == 2 || s.EstatSolicitut == 3) && Ara.Date <= s.DataFinal && Ara.Date >= s.DataInicial && s.FKTreballador.IdDepartament == IdDepartament)
.AsNoTracking();
foreach (Guid aux in treballadorsDepartament)
{
int? tipusMov = QueryFitxatge
.Where(f => f.IdTreballador == aux)
.OrderBy(m => m.HoraAjustada)
.Select(f => f.TipusMoviment)
.Last();
if (tipusMov != null && tipusMov == 0)
{
TreballadorsPresents ;
continue;
}
else if (QuerySollicitud.Any(s => s.IdTreballador == aux))
{
TreballadorsVacances ;
continue;
}
TreballadorsAbsents ;
}
uj5u.com熱心網友回復:
你可以這樣做:
var maxDateSignsByEmployee = from sign in AppDbContext.Signings.Where(s => s.Time.Date == DateTime.Now.Date)
group sign by sign.EmployeeId into res
select new{
EmpId = res.Key,
MaxDate = resg.Max(x => x.Time)
};
var list = from e in AppDbContext.Employees
join s in AppDbContext.Signings.Where(s => maxDateSignsByEmployee.Where(m => m.EmpId == s.EmployeeId && m.MaxDate == s.Time).Count() > 0)
on e.WorkerId equals s.EmployeeId
where e.DepartmentId == DepartmentId
select new Aux2()
{
Id = e.EmployeeId,
Type = s.SignType,
};
它應該是你需要的。這是一個基本的回應,你可以優化它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/448981.html
標籤:C# sql 林克 .net-core ef-core-6.0
