用 where 解释 Sql 并向 linq 声明给出不同的结果

Interpreting Sql with where and having statement to linq giving different results

请 - 我有这个 SQL 声明:

SELECT FK_ClassId, LectureDays
FROM tbl_TimeTables
WHERE Term = 'First Term' 
  AND FK_session = 4 
  AND fk_classId = 1 
  AND (fk_subjectid <> 1)
GROUP BY FK_classId, LectureDays
HAVING (COUNT(*) < 6)

这个returns这个结果:

Image Embedded Here, giving the right result

但是当我解释为 linq 时,我得到了不同的结果:

Tbl_TimeTables.GroupBy(x => new { x.FK_Session, x.Term, x.LectureDays,   
x.FK_ClassId, x.FK_SubjectId })
.Where(grp => grp.Count() < 6 && grp.Key.FK_Session == 4 && grp.Key.Term ==   
"First Term" && grp.Key.FK_ClassId == 1 && grp.Key.FK_SubjectId != 1)
.Select(grp => new 
{
  LectureDay = grp.Key.LectureDays,
  ClassId = grp.Key.FK_ClassId
})

Wrong Results Picture Link here

请看我的代码,我做错了什么?

谢谢

蒂姆

根据 Matt Gibson 的建议,这是 linq 查询的正确方式:

Tbl_TimeTables
.Where(x => x.FK_Session == 4 && x.Term == "First Term" && x.FK_ClassId == 1   
&& x.FK_SubjectId != 1)
.GroupBy(x => new { x.FK_ClassId, x.LectureDays })
.Where(grp => grp.Count() < 6)
.Select(grp => new 
{
  ClassId = grp.Key.FK_ClassId,
  LectureDay = grp.Key.LectureDays
})

这与 sql 完全一样 还要指出的是 link: http://www.dotnettricks.com/learn/sqlserver/definition-use-of-group-by-and-having-clause 帮助我理解了 having 语句的工作原理,这有助于了解 Matt 在说什么。