2014-02-18 75 views
1

如何將此查詢使用內連接,左外連接,group by和兩個計數轉換爲linq?左外連接和多重計數SQL到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) 
       }; 
+0

你有什麼試過的?我會給你一個提示,你使用Where,GroupBy,Select和兩個Join。所有這些都可以直接轉換成LINQ。 – evanmcdonnal

+0

請告訴我們你到目前爲止 - 我們需要看到你已經付出了一些努力,並看看你到底在哪裏陷入困境。 – user2366842

+0

好吧我剛更新 – Talley

回答

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() 

S QL:COUNT(r.ChoiceID)

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