我有一个表学生,其中包含以下专栏
StudentId SemesterId ExamYearId
1 1 1
1 2 2
1 3 3
3 1 1
3 2 2
3 3 4
7 1 1
7 3 4
8 1 1
8 2 2
我想要一个查询来获取semesterid=3
和examyearid=3
没有数据的所有学生,但是同一个学生应该拥有semesterid=2
的数据。
在这种情况下,它应该返回studentid=8
,因为studentid=8
包含semesterid=2
和examyearid=2
的数据,但examyearid=3
和semesterid=3
没有数据。
基本上我希望能够输入semesterid
和examyearid
,并找出哪些studentid
尚未填充semesterid
和examyearid
的数据。
答案 0 :(得分:1)
DECLARE @SemesterId INT
,@ExamYearId INT
SET @SemesterId = 3;
SET @ExamYearId = 3;
SELECT *
FROM TableName t
WHERE EXISTS (SELECT 1
FROM TableName
WHERE SemesterId = @SemesterId - 1
AND ExamYearId = @ExamYearId - 1
AND t.StudentId = StudentId )
AND NOT EXISTS (SELECT 1
FROM TableName
WHERE SemesterId = @SemesterId
AND ExamYearId = @ExamYearId
AND t.StudentId = StudentId )
答案 1 :(得分:0)
SELECT st1.*
FROM Student st1
left join Student st2
on st1.id = st2.id
and st1.Semesterid=2
and st2.Semesterid=3
and st2.Examyearid=3
where st2.id is null