sqlquery丢失

时间:2015-05-18 18:41:45

标签: sql sql-server tsql

我有一个表学生,其中包含以下专栏


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=3examyearid=3没有数据的所有学生,但是同一个学生应该拥​​有semesterid=2的数据。

在这种情况下,它应该返回studentid=8,因为studentid=8包含semesterid=2examyearid=2的数据,但examyearid=3semesterid=3没有数据。

基本上我希望能够输入semesteridexamyearid,并找出哪些studentid尚未填充semesteridexamyearid的数据。

2 个答案:

答案 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