I have an SQL query (below) that essentially takes a student from tbStudents, and then gets the most recent term (a number, but stored as a string) in tbTerms.
There is a one-to-many relationship with a student in tbStudents to a term record in tbTerms. Example:
tbStudents:
StudentId FirstName LastName
12345 John Smith
12346 Jane Doe
tbTerms:
StudentId Term
12345 1234
12345 1235
12345 1236
12346 1233
12346 1234
Desired:
StudentId FirstName LastName Term
12345 John Smith 1236
12346 Jane Doe 1234
SQL Query:
select tbStudents.student_id, tbStudents.user_id, tbStudents.firstname, tbStudents.lastname, v.rTerm
from tbStudents
inner join (
select tbTerms.student_id, MAX(tbTerms.term) as rTerm
from tbTerms
group by tbTerms.student_id
) v on v.student_id = tbStudents.student_id
I’ve been trying to get this all into one LINQ statement, but I’m having trouble. Is there anyway to do this in one statement? Or must it be done in multiple statements. Thanks in advanced.
Edit: C# code of what I have tried.
var students = (from s in dockDb.tbStudents
join t in dockDb.tbTerms on s.student_id equals t.student_id
into pairs
from p in pairs
select new { UserId = s.user_id, StudentId = s.student_id, Term = p.term } ).ToList();
Output is similar to:
StudentId FirstName LastName Term
12345 John Smith 1234
12345 John Smith 1235
12345 John Smith 1236
12346 Jane Doe 1233
12346 Jane Doe 1234
Edit #2: I’m using Entity Framework for data. I’m not sure if this affects anything, but most of the solutions are ‘Syntactically incorrect’ when I attempt them.
Should be possible. Try this:
Breaking it down, the first two lines define the domain in which to search; namely, the inner-joined combination of Students and Terms, linked by StudentId. Each unique combination of Student and Term are put into an anonymous type, and then those instances are grouped by each unique Student into a Lookup (a read-only collection of IEnumerables referenced by key). The, we can select the key’s (Student’s) vital info, and in the list of terms, find the one with the highest value (which will be the most recent).