简体   繁体   English

左外部联接和多个计数到LINQ的SQL

[英]Left outer join and multiple counts SQL to LINQ

How would this query using an inner join, left outer join, group by and two counts be converted to linq? 使用内部联接,左外部联接,分组依据和两个计数的查询如何转换为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;

This is what I have done so far: 到目前为止,这是我所做的:

            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)
                };

You need to group using an anonymous class. 您需要使用匿名类进行group This will allow you to access all your tables in your select statement 这将允许您访问select语句中的所有表

group new { c, f, rf } by c.EndowmentID into grouped

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

This can be written by first selecting the f.CriterionID column, Distinct() , Count() 这可以通过首先选择f.CriterionIDDistinct()Count()来编写

RequiredCriteria = grouped.Select(x => x.f.CriterionID).Distinct().Count()

SQL: COUNT(r.ChoiceID) SQL: COUNT(r.ChoiceID)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM