2014-12-09 131 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