LINQ with subquery,group by和having count

时间:2017-02-18 13:04:20

标签: c# linq

我刚开始用LINQ开始编写查询,这就是为什么我对它不是很熟悉。我的查询在SQL中运行得很好,但我想在它的LINQ表达式中替换它。

SELECT DISTINCT Libelle
FROM Question, Connaissance
WHERE Question.ID_Q = Connaissance.ID_Question and ID_Q = (SELECT ID_Question
FROM Connaissance
GROUP BY ID_Question
HAVING COUNT(ID_Reponse) >= ALL(SELECT COUNT(ID_Reponse)
FROM Connaissance
GROUP BY ID_Question))

(Libelle是问题表中问题的名称)

我尝试过类似的东西:

var question = from q in dc.Question
               join a in dc.Connaissance on q.ID_Q equals a.ID_Question
               group q by a.ID_Question into grp
               where grp.Count() >= ???

问题是我不知道如何转换这部分:>= ALL(SELECT COUNT(ID_Reponse)。我试图在互联网上搜索类似的东西,但没有找到任何东西。

如果有人能帮助我,我会非常感激......

2 个答案:

答案 0 :(得分:1)

会这样做吗?

var question =
    from q in dc.Question
    join a in dc.Connaissance on q.ID_Q equals a.ID_Question
    group q by a.ID_Question into grp
    where grp.Count() >= dc.Connaissance.Select(y => y.ID_response).Distinct().Count()

答案 1 :(得分:0)

将来有助于说明预期结果。据我所知

(SELECT ID_Question
FROM Connaissance
GROUP BY ID_Question
HAVING COUNT(ID_Reponse) >= ALL(SELECT COUNT(ID_Reponse)
FROM Connaissance
GROUP BY ID_Question))

只是获得最多答案的所有问题的问题ID列表。由于此部分中的ALL仅确保答案计数大于或等于所有问题的所有答案计数的问题。

COUNT(ID_Reponse) >= ALL(SELECT COUNT(ID_Reponse)
FROM Connaissance
GROUP BY ID_Question)

所以,根据您的理解,您想要所有与最多答案相关的问题的名称,请尝试这个

var maxAnswerCount = dc.Connaissance.GroupBy(answer => answer.ID_Question)
                                    .Select(answerGroup => answerGroup.Count())
                                    .Max();

var questions = (from answer in dc.Connaissance
                 group answer by answer.ID_Question into answerGroup
                 where answerGroup.Count() == maxAnswerCount
                 from question in dc.Question
                 where answerGroup.Key == question.ID_Q
                 select question.Libelle).Distinct()

当然,如果我还没有理解最终结果是什么,请澄清。