我想在Linq to EF查询中使用Average函数和Count。因此,如果我必须用t-sql中的代码部分解释我尝试实现的内容以便更清楚地理解,您可以看看下面的内容,
select s.SalesPointId, count(*) as ipp
from ScoreItem si
inner join Score s on s.Id = si.ScoreId
where si.ResearchGroupType = 0 and si.IsValidForSalesPoint = 1
group by s.SalesPointId
select avg(ipp)
from (
select s.SalesPointId, count(*) as ipp
from ScoreItem si
inner join Score s on s.Id = si.ScoreId
where si.ResearchGroupType = 0 and si.IsValidForSalesPoint = 1
group by s.SalesPointId
)
因此,我在Linq查询中编写了以下代码,
List<CvmNameAndValue> AnatolianSalesHeadshipIPPScore = (from si in db.ScoreItem
join s in db.Score on si.ScoreId equals s.Id
join sp in db.SalesPoint on s.SalesPointId equals sp.Id
where (si.ResearchGroupType == ResearchGroupType.ScoreCard && si.IsValidForSalesPoint && sp.CompanyId == ContextData.User.CompanyId && s.ProjectPeriodId == ProjectPeriodId && spIds.Contains(sp.Id))
group s by s.SalesPointId into g
select new CvmNameAndValue
{
Name = SystemSetting.Label_AnatolianSalesHeadshipIPPScore,
Value = g.Average(x => db.Score.Count()).ToString()
})
.ToList();
retVal.Data.DataGroup = AnatolianSalesHeadshipIPPScore.ToList();
return retVal;
但是,不幸的是他们没有给我相同的结果,所以如果你对我的逻辑错误有任何建议,请感到自由并与我分享,
答案 0 :(得分:0)
最后我已经解决了我的问题,所以如果你需要这样的东西,它可以解决你的问题,
double AnatolianSalesHeadshipIPPScore = 0;
AnatolianSalesHeadshipIPPScore = (from si in db.ScoreItem
join s in db.Score on si.ScoreId equals s.Id
join sp in db.SalesPoint on s.SalesPointId equals sp.Id
where (si.ResearchGroupType == ResearchGroupType.ScoreCard && si.IsValidForSalesPoint && sp.CompanyId == ContextData.User.CompanyId && s.ProjectPeriodId == ProjectPeriodId)
group si by s.SalesPointId into g
select new
{
sid = g.Key,
count = g.Count()
}).Average(m => m.count);