[英]How can we perform a select into another select using Linq c# left join, count , sum, where
How can I convert my sql code into Linq format : 如何将我的sql代码转换为Linq格式:
How can we perform a select into another select using Linq c# : 我们如何使用Linq c#将一个选择转换为另一个选择:
My sql code : 我的SQL代码:
SELECT DepartementProjects.Label, a.Number FROM
(SELECT DepartementProjects.Label ,count(1) as Number FROM DepartementProjects
inner join Absences on DepartementProjects.Id = Absences.DepartementProjectID
where Absences.Profil='SHT'
group by DepartementProjects.Label ) a right join DepartementProjects on DepartementProjects.Label = a.Label;
My attempt : 我的尝试:
var AbsByDepartmentADM = from department in _dbContext.DepartementProjects
join abs in _dbContext.Absences on department.Id equals abs.DepartementProjectID
into groupedResult
from groupedResultRight in groupedResult.DefaultIfEmpty()
group groupedResultRight by department.Label into grouped
let NumberOfAbsence = grouped.Count(t => t.DepartementProjectID != null)
let WorkedHours = grouped.Sum(a => a.WorkedHours != null ? a.WorkedHours : 0)
select new
{
DepartmentId = grouped.Key,
NumberOfAbsence,
WorkedHours,
AbsencesHours = (8 * NumberOfAbsence - WorkedHours),
};
If you are trying to translate SQL, translate any subselects first, then the main select, and translate in LINQ phrase order. 如果要翻译SQL,请先翻译所有子选择,然后再翻译主选择,然后按LINQ短语顺序翻译。 Also, your LINQ adds some values not in the SQL, so I didn't try to change the SQL to match:
另外,您的LINQ会在SQL中添加一些值,因此我没有尝试更改SQL以使其匹配:
var sub = from dept in _dbContext.DepartementProjects
join abs in _dbContext.Absences on dept.Id equals abs.DepartementProjectID into absj
from abs in absj
where abs.Profil == "SHT"
group abs by dept.Label into absg
select new { Label = absg.Key, Number = absg.Count() };
var ans = from dept in _dbContext.DepartementProjects
join a in sub on dept.Label equals a.Label into lnj
from ln in lnj.DefaultIfEmpty()
select new { dept.Label, ln.Number };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.