I have two tables:
STUDENT GRADES
---------- ----------
id id
name person_id
address date
city test_name
phone grade
Each Student will have several entries in the Grades table. I am wondering if it is possible using SQL (Postgres) to select all students along with their latest grade information. I basically want a result table that looks like the following, where date, test_name, and grade are for the latest result (by date).
LATEST_GRADES
----------------
id
name
address
city
phone
grade_id
date
test_name
grade
Any help would be greatly appreciated, thanks.
EDIT: ADDED SOLUTION QUERY
SELECT * FROM
students s
JOIN (SELECT DISTINCT ON (person_id) person_id, date, test_name, grade
FROM grades
ORDER BY person_id, date DESC) g
ON s.id = g.person_id;
Yes, it’s possible. The clause you’re looking for is “DISTINCT ON“. With it you can easily do the query without subselects and multiple scans of the same table.
In docs, please notice the ON part of “DISTINCT ON”.