查询查找表的相同值

时间:2013-11-03 03:33:47

标签: sql sql-server

我有一张桌子:

courseTracker(
        student int
        courseID int
)

我想找到每个与学生'B'具有相同课程的学生

1 个答案:

答案 0 :(得分:0)

我不确定你想要哪两个,所以我包括了两个。

这将使至少有一门课程的学生回归B:

SELECT DISTINCT student FROM coursetracker
WHERE courseID IN (
    SELECT courseID FROM coursetracker WHERE student = 'B'
)

这将返回与B课程完全相同的学生:

SELECT student FROM (SELECT DISTINCT student FROM coursetracker) c
WHERE NOT EXISTS (
    SELECT * FROM coursetracker c1
        FULL JOIN coursetracker c2 ON c1.courseId = c2.courseId
            AND c1.student = c.student AND c2.student = 'B'
    WHERE c1.courseID IS NULL OR c2.courseID IS NULL
)