Self join twice - once for the match, and again for to find a different match:
SELECT s.studentid, st.studentid, s.year, s.quarter, s.courseid
FROM enrolled s
JOIN enrolled st ON st.COURSEID = s.COURSEID
AND st.quarter = s.quarter
AND st.year = s.year
AND s.studentid < st.studentid
JOIN enrolled e2 ON e2.COURSEID != s.COURSEID
AND e2.quarter = s.quarter
AND e2.year = s.year
AND e2.studentid = st.studentid
Output:
| STUDENTID | OTHER_STUDENTID | YEAR | QUARTER | COURSEID |
|-----------|-----------------|------|---------|----------|
| 60973 | 90421 | 2013 | Spring | 2987 |
| 60973 | 90421 | 2013 | Spring | 8772 |
See SQLFiddle
Notes:
- You want an (inner) join, not a left join
- Use
s.studentid < st.studentid
to stop:- students joining to themselves, and
- both sides of pairs from displaying
- Use a different course for the second join but the same other student id