我是新来的,所以如果我犯了任何错误,我会道歉。我编写了以下SQL代码来检索特定教师中每个用户提交的数量。
declare @faculty as int = 1
SELECT COUNT(ew_student.sName) AS Submissions, ew_student.sEmail, ew_faculty.nFaculty
FROM ew_student
INNER JOIN ew_submission ON ew_student.sId = ew_submission.sId INNER JOIN
ew_faculty ON ew_student.sFaculty = ew_faculty.fId
WHERE ew_faculty.fId = @faculty
GROUP BY ew_student.sEmail, ew_faculty.nFaculty
通过MS SQL Server Management运行此查询会返回我期望的结果,但是在我的ASP.NET Web应用程序中,我在编写LINQ表达式时遇到了困难。
我的数据库上下文称为“db”。这是我到目前为止所得到的,但它返回了错误的结果。
var stats = from ew_submissions in db.ew_submissions
where ew_submissions.ew_student.ew_faculty.fId == facultyId
group new { ew_submissions.ew_student, ew_submissions.ew_student.ew_faculty } by new
{
ew_submissions.ew_student.sEmail,
ew_submissions.ew_student.sName,
ew_submissions.ew_student.ew_faculty.nFaculty
} into g
select new
{
Submissions = g.Count(),
g.Key.sName
};
return stats.ToList();
我想检索特定用户提交的提交数量,但上面的LINQ表达式总是为每个用户返回1。
答案 0 :(得分:1)
您切换了要分组的位置(值)和按键(键):
var stats = from ew_submissions in db.ew_submissions
where ew_submissions.ew_student.ew_faculty.fId == facultyId
group ew_submissions.ew_student.sName by new
{
ew_submissions.ew_student.sEmail,
ew_submissions.ew_student.ew_faculty.nFaculty
} into g
select new
{
Submissions = g.Count(),
g.Key.sName
};
return stats.ToList();
另请注意,当您按sEmail
和nFaculty
进行分组时,您不希望也按sName
进行分组,因为这样您可能会获得许多计数结果。