SELECT s11.room, s11.hall, s11.lastname AS lastname1, s11.firstname AS firstname1, s12.lastname AS lastname2, s12.firstname AS firstname2 FROM (SELECT d1.room, d1.hall, d1.sid1, CASE WHEN d1.sid2<>d1.sid1 THEN d1.sid2 ELSE Null END AS sid2 FROM ( SELECT DISTINCT s1.room, s1.hall, (SELECT TOP 1 studentID FROM students s2 WHERE s2.room = s1.room and s2.hall = s1.hall and s2.periodID = s1.periodID ORDER BY StudentID ASC) AS Sid1, (SELECT TOP 1 studentID FROM students s3 WHERE s3.room = s1.room and s3.hall = s1.hall and s3.periodID = s1.periodID ORDER BY studentID DESC) AS sid2 FROM students s1) d1) d2 inner join students s11 on d2.sid1 = s11.studentID and d2.room = s11.room and d2.hall = s11.hall left outer join students s12 on d2.sid2 = s12.studentID and d2.room = s12.room and d2.hall = s12.hall where s11.hall = 'BREESE' and s11.periodid=4 order by s11.room>The following simplified query will return the list of rooms with student id's. You can use it as starting point for your query.
SELECT room, sid1, > CASE WHEN sid2<>sid1 THEN sid2 ELSE Null END AS sid2 > FROM ( >SELECT DISTINCT s1.Room, > (SELECT TOP 1 StudentId FROM students s2 > WHERE s2.room = s1.room > ORDER BY StudentId) AS Sid1, > (SELECT TOP 1 StudentId FROM students s3 > WHERE s3.room = s1.room > ORDER BY StudentId DESC) AS sid2 > FROM students s1) d1 >>>I have a table of students. In this students table, I have a name and room they are staying in.