如何按表列过滤LINQ查询并获取计数

时间:2014-12-09 11:26:43

标签: c# sql-server linq entity-framework

我试图根据他们的状态获取学生名单,按学院分组。

所以我有三张桌子,学生和学院。每个学生记录都有一个状态,可以是“前景”,“接受”和“接受”。或者' WebApp'。我需要做的是根据所选状态获取学生名单,然后显示学院的名称,以及进入该学院并将其状态设置为传入状态的学生人数.I认为这需要是一个聚合查询,因为计数来自字符串状态字段。

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

接受=状态('接受') WebApps =状态(' WebApp') 总计=总和(Accpets + WebApps)

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

试试这个http://www.linqpad.net/ 它是免费的,您可以将linq转换为SQL查询

相关问题