我有以下表格
student(student_id, name)
assignment(student_id, course_code, assignment number)
我正在尝试编写一个查询来返回那些已为特定课程提交了作业编号1而不是作业编号2的学生
我已经编写了以下查询,但很难在每个课程的基础上返回结果。有什么建议吗?
SELECT name, a.student_id, course_code
FROM assignment a INNER JOIN student s
on a.student_id = s.student_id
WHERE assignment_number = 1
AND assignment_number != 2
答案 0 :(得分:2)
SELECT name, a.student_id, course_code
FROM assignment a INNER JOIN student s
on a.student_id = s.student_id
WHERE assignment_number = 1
AND not exists (select * from
assignment a2 inner join student s2
where a2.student_id = s2.student_id
and s2.student_id = s.student_id
and a2.assignment_number = 2)
这是在行动中看到它的小提琴: http://sqlfiddle.com/#!2/48997/2
答案 1 :(得分:1)
SELECT
s.name,
s.student_id,
a.course_code
FROM
assignment a
INNER JOIN
student s
ON
a.student_id = s.student_id
WHERE
assignment_number in( 1,2 )
GROUP BY
s.name,
s.student_id,
a.course_code
HAVING max(assignment_number) = 1
答案 2 :(得分:0)
已完成作业1的学生名单,但未已完成作业2:
select s.name, a.student_id, a.course_code
from assignment a
inner join student s on a.student_id = s.student_id
where a.student_id in
(Select student_id from assignment
where assignment_id = 1) -- All students that submitted Assignment 1
and a.assignment_id !=2