【问题标题】:Interpreting Sql with where and having statement to linq giving different results用 where 解释 Sql 并对 linq 给出不同的结果
【发布时间】:2018-01-06 09:30:56
【问题描述】:

请 - 我有这个 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)

这会返回这个结果:

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

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

谢谢

提姆

【问题讨论】:

  • 你不只是在每个查询中按不同的东西分组吗?
  • 嗨,马特,如果您能指出正确的方向,那我不知道如何纠正。谢谢
  • 感谢 marc_s 和 Aomine 的编辑
  • 事实上,我从来不知道语言的力量,Matt Gibson,你实际上给我指明了正确的方向,我以前看不到,但现在我明白了。我在下面发布了正确的 linq 查询。谢谢
  • 不客气。

标签: c# sql linq where having


【解决方案1】:

根据 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 完全一样 还要指出,这个链接:http://www.dotnettricks.com/learn/sqlserver/definition-use-of-group-by-and-having-clause 帮助我理解了有语句的工作原理,这有助于了解马特在说什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多