I'm doing Stanfords introduction to DB course and this is one of the homework assignments. My code does the job well, but I don't really like it how I reused the same SELECT-FROM-JOIN part twice:
SELECT name, grade
FROM Highschooler
WHERE
ID IN (
SELECT H1.ID
FROM Friend
JOIN Highschooler AS H1
ON Friend.ID1 = H1.ID
JOIN Highschooler AS H2
ON Friend.ID2 = H2.ID
WHERE H1.grade = H2.grade
) AND
ID NOT IN (
SELECT H1.ID
FROM Friend
JOIN Highschooler AS H1
ON Friend.ID1 = H1.ID
JOIN Highschooler AS H2
ON Friend.ID2 = H2.ID
WHERE H1.grade <> H2.grade
)
ORDER BY grade, name
This is the SQL schema for the two tables used in the code:
Highschooler(ID int, name text, grade int);
Friend(ID1 int, ID2 int);
I had to query all the Highschoolers that only have friends in the same grade, and not in any other grades. Is there a way to somehow write the code bellow only once, and reuse it two times for the two different WHERE clauses = and <>?
SELECT H1.ID
FROM Friend
JOIN Highschooler AS H1
ON Friend.ID1 = H1.ID
JOIN Highschooler AS H2
ON Friend.ID2 = H2.ID
EDIT: We are required to provide SQLite code.