我正在尝试在LINQ C#中编写以下SQL查询,但是无法在group子句之后获取列。
SQL查询
/*get the number of questions by subject*/
select b.SubjectID, b.SubjectName, count(*) AS count
from QuestionsTable a, SubjectTable b
where a.SubjectID is not null AND a.SubjectID = b.SubjectID
GROUP BY a.SubjectID
LINQ查询
var result =(from a in db1.QuestionsTables
join b in db1.SubjectTables
on a.SubjectID equals b.SubjectID
where a.SubjectID != null
group a by a.SubjectID into g
select new { a.QuestionID, a.SubjectID, b.SubjectName
}).ToList();
答案 0 :(得分:4)
由于您按a.Subject.ID
查询组,但选择b.SubjectID
和b.SubjectName
,您的SQL将无法正确执行。通常,您还应该将单个选定的字段包含在GROUP BY
列表中。
(据我所知,有些SQL服务器可以处理功能相关字段,因此他们可以处理您的查询。但总的来说这是错误的。)
所以你的工作查询应该是:
SELECT b.SubjectID, b.SubjectName, COUNT(*) AS Count
FROM QuestionsTable a, SubjectTable b
WHERE a.SubjectID is not null AND a.SubjectID = b.SubjectID
GROUP BY b.SubjectID, b.SubjectName
你的LINQ应该是
from a in db.QuestionsTable
join b in db.SubjectTable
on a.SubjectId equals b.SubjectId
where a.SubjectId != null
group b by new { b.SubjectId, b.SubjectName } into g
select new { g.Key.SubjectId, g.Key.SubjectName, g.Count() }
答案 1 :(得分:0)
虽然它可以按你提出的方式制作,但是可以用更简单的自然方式获得相同的结果,而不涉及分组,例如
// get the number of questions by subject
var result =
(from s in db1.SubjectTables
select new
{
s.SubjectID,
s.SubjectName,
Count = db1.QuestionsTables.Count(q => q.SubjectID == s.SubjectID)
}).ToList();
更新:无论是什么down,我都坚信这是解决这一特定问题的正确方法 - 简单而自然。为什么要对已经分组的内容进行分组(按主键)。