Let's see if I'm interpreting you correctly here.
You have an entity teacher, an entity student, and an entity grade, like this:
teacher --1 grade 1-- student
(one grade can have multiple teachers and multiple students, a student and a teacher can have one grade)
You want all Students that belong to the same grade as the teacher. That would make an xpath pretty easy, as there is only one relation between a teacher and a student, and that is via grade. it would look (pseudocode) something like this:
student_grade/grade/teacher_grade = $teacher
(or [%currentObject%] instead of $teacher if you're working from a page)
Note that in a lot of cases, Mendix writes the xpath for you. Both in a microflow and page, if you select the 'entity' for your grid or retrieve, the top of the list will always represent objects that are readily available for a retrieve over association. In your case; teacher. You can simply drill down under this object (teacher) over the reference to grade, to student. Mendix does the rest.