SQL - Find the grade of students who only like students in the same grade

前提是你 提交于 2019-12-05 14:04:14

So we want to find students for whom there are no students in other grades they have a friendship relationship, right? This is one way to express that:

select * from highschooler h
where not exists
(select 1 from highschooler h2 where h2.grade != h.grade and exists
(select 1 from friends f where (f.id1 = h.id or f.id2 = h.id) and (f.id1 = h2.id or f.id2 = h2.id)))
order by grade, name

EDIT: If you also require them to have at least one friend, you'll need to check for that too

My solution:

SELECT name, grade
FROM Highschooler
WHERE ID NOT IN
(SELECT ID1
FROM Friend F1 JOIN Highschooler H1
ON H1.ID = F1.ID1
JOIN Highschooler H2
ON H2.ID = F1.ID2
WHERE H1.grade <> H2.grade)
ORDER BY grade, name

Essentially, the inner sub-query returns a relation of students with friends that have varying grades (where H1.grade <> to H2.grade). Then the outer query simply lists all students that don't feature in this inner relation.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!