SQL- 找出所有朋友的分数都低于 10 的所有学生

SQL- Find all students who all of their friends have score less than 10

我必须使用 SQLServer 为我的数据库作业编写一些简单的查询。架构已在问题中提供:

students(student_id, name);
friends(student_id, friend_id);
db_grades(student_id, grade);

对于每对朋友,(x, y)(y, x) 两行将添加到 friends table

Find all students, who all of their friends have a score of less than 10

首先我尝试使用 GROUP BY 来解决这个问题,然后我写了下面的查询。

Select Distinct s.name, MAX(g.grade)
       From (students s inner join friends f on s.student_id = f.student_id), db_grades g
       Where f.friend_id = g.student_id
       Group by f.friend_id, s.name
       Having MAX(g.grade) < 10;

在第二次尝试中,我想使用 IN 关键字来实现它,但它也无法正常工作。

Select distinct s.name
    From students s  join friends f on s.student_id = f.student_id
    Where f.friend_id not in
    (
       Select f.friend_id
       From  db_grades g1
       Where g1.student_id = f.friend_id and g1.grade > 10
    )

如果你能帮助我编写正确的查询,我将不胜感激。

聚合是一种选择:

SELECT s.student_id, s.name
FROM students s
INNER JOIN friends f
    ON f.student_id = s.student_id
INNER JOIN db_grades g
    ON g.student_id = f.friend_id
GROUP BY s.student_id, s.name
HAVING COUNT(CASE WHEN f.grade >= 10 THEN 1 END) = 0;

另一种选择是使用 NOT EXISTS。请注意,此选项与带有 INNER JOINHAVING 之间的区别在于,此选项包括那些根本没有朋友的选项。

SELECT s.student_id, s.name
FROM students s
WHERE NOT EXISTS (SELECT 1
    FROM friends f
    INNER JOIN db_grades g
        ON g.student_id = f.friend_id
    WHERE f.student_id = s.student_id
      AND g.grade >= 10
);