左外连接和多个计数SQL到LINQ

时间:2014-02-18 19:19:56

标签: c# linq sql-to-linq-conversion

如何使用内部联接,左外部联接,分组依据和两个计数的查询转换为linq?

SELECT
    c.EndowmentID,
    COUNT(DISTINCT f.CriterionID) AS RequiredCriteria,
    COUNT(r.ChoiceID) AS Response
FROM
    Criteria c
INNER JOIN
    Filters f
ON
    c.ID = f.CriterionID
LEFT OUTER JOIN 
    Responses r
ON
    f.ChoiceID = r.ChoiceID
WHERE
    f.IsRequirement = 1
GROUP BY
    c.EndowmentID;

这是我到目前为止所做的:

            var result =
                from c in context.Criteria
                join f in context.Filters on c.ID equals f.CriterionID
                join r in context.Responses on f.ChoiceID equals r.ChoiceID into resfil
                from rf in resfil.DefaultIfEmpty()
                group rf by c.EndowmentID into grouped
                select new 
                {
                    EndowmentID = grouped.Key,
                    Requirements = grouped.Count(t=>t.CriterionID),
                    Response = grouped.Count(t=>t.ChoiceID)
                };

1 个答案:

答案 0 :(得分:0)

您需要group使用匿名类。这样您就可以访问select声明

中的所有表格
group new { c, f, rf } by c.EndowmentID into grouped

SQL:COUNT(DISTINCT f.CriterionID) AS RequiredCriteria,

首先选择f.CriterionID列,Distinct()Count()

即可编写
RequiredCriteria = grouped.Select(x => x.f.CriterionID).Distinct().Count()

SQL:COUNT(r.ChoiceID)

Response = grouped.Select(x => x.rf.ChoiceID).Count()