2014-12-09 44 views
2

我試圖根據他們的狀態獲取學生列表,並按他們的大學分組。如何按表列過濾LINQ查詢並獲得計數

所以我有三張桌子,學生和學院。每個學生記錄都有一個狀態,可以是「展望」,「接受」或「WebApp」。我需要做的是根據所選狀態獲取學生名單,然後顯示學院的名稱以及進入該大學的學生人數,並將他們的狀態設置爲通過狀態。我認爲這需要是一個聚合查詢,因爲計數來自字符串狀態字段。

enter image description here

我不知道如何做到這一點的MS SQL,因爲計數從同一個表來了,它是基於狀態字段的值。

這是我的查詢的開始,它採用搜索參數,但我無法弄清楚如何篩選狀態以返回計數。

SELECT Colleges.Name, [Status], Count([Status]) 
FROM Students 
JOIN Colleges ON Students.UniversityId = Colleges.id OR Students.+College = Colleges.Name 
GROUP BY Students.[Status], Colleges.Name 
ORDER BY Colleges.Name; 

enter image description here

接受=狀態( '接受') 的WebApp =狀態( 'Web應用程序') 總計= SUM(Accpets +的WebApp)

+0

linq或SQL解決方案,你正在尋找? – Pleun 2014-12-09 11:40:12

回答

3
Select 
Colleges.Name, 
SUM(Case when Students.Status like 'Accepted' then 1 else 0 end) Accepts, 
SUM(Case when Students.Status like 'WebApp' then 1 else 0 end) WebApps, 
COUNT(*) Total 
from Students 
join Colleges on Students.UniversityId = Colleges.Id OR Students.CurrentCollege = Colleges.Name 
Group by Colleges.Name 

的LINQ:

var results = 
(from c in db.Colleges // db is your DataContext        
select new 
{ 
CollegeName = c.Name, 
AcceptedStatus = db.Students.Count(r => r.Status.ToUpper() == "ACCEPTED" && (r.UniversityId == c.Id || r.CurrentCollege == c.Name)), 
WebAppStatus = db.Students.Count(r => r.Status.ToUpper() == "WEBAPP" && (r.UniversityId== c.Id || r.CurrentCollege == c.Name)), 
Total = db.Students.Count(s => s.UniversityId == c.Id || s.CurrentCollege == c.Name) 
}).ToList(); 
+0

現在,如果我只能弄清楚如何將其轉換爲LINQ查詢... – 2014-12-09 12:03:24

+0

@CarlWeis更新了我的答案。 – 2014-12-09 12:21:11