简体   繁体   中英

How to filter LINQ query by table column and get count

I'm trying to get a list of students based on their status, grouped by their college.

So I have three tables, Students and Colleges. Each student record has a status, that can be 'Prospect', 'Accepted' or 'WebApp'. What I need to do is get a list of students based on the status selected and then display the College's name, along with the number of students that go to that college and have their status set to the status passed in. I think this needs to be an aggregate query, since the counts are coming from the string Status field.

在此处输入图片说明

I'm not sure how to do this in MS SQL, since the count is coming from the same table and it's based on the status field's value.

Here is the start of my query, which takes in the search parameters, but I can't figure out how to filter on the status to return the counts.

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;

在此处输入图片说明

Accepts = Status('Accepted') WebApps = Status('WebApp') Total = Sum(Accpets + WebApps)

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

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

免费试用此http://www.linqpad.net/ ,您可以将linq转换为sql查询

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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