2010-09-08 35 views
1

从StudentDetails表TSQL查找不完整的课程

StudentDetails

SID Name CourseCompleted 

1 Andrew CS001 
1 Andrew CS002 
1 Andrew CS003 

2 Grey  CS001 
2 Grey  CS005 
2 Grey  CS002 

3 Jon  CS002 
3 Jon  CS005 
3 Jon  CS008 

如何产生如下因素输出(当然不是每个学生完成)

SID Name Course Not Completed 

1 Andrew CS005 
1 Andrew CS008 

2 Grey  CS003 
2 Grey  CS008 

3 Jon  CS001 
3 Jon  CS003 
+0

你有所有的课程表吗? – 2010-09-08 12:43:48

+0

我们是否应该不需要完整的课程列表?所以人们可以说出“未完成”是什么。 – CyberDude 2010-09-08 12:43:53

+0

这只是测试同一张表,所以不需要课程表 – Gopi 2010-09-08 12:58:02

回答

1
select distinct a.SID, a.Name, b.CourseCompleted as `Course Not Completed` 
from StudentDetails a, 
(select distinct CourseCompleted from StudentDetails) b 
where not exists 
(select 1 from StudentDetails where SID = a.SID and CourseCompleted = b.CourseCompleted) 
order by a.SID 
0
With StudentDetails As 
(
SELECT 1 SID, 'Andrew' Name, 'CS001' CourseCompleted union all 
SELECT 1, 'Andrew', 'CS002' union all 
SELECT 1 , 'Andrew' , 'CS003' union all 
SELECT 2 , 'Grey' , 'CS001' union all 
SELECT 2 , 'Grey' , 'CS005' union all 
SELECT 2 , 'Grey' , 'CS002' union all 
SELECT 3 , 'Jon' , 'CS002' union all 
SELECT 3 , 'Jon' , 'CS005' union all 
SELECT 3 , 'Jon' , 'CS008' 
), 
Courses AS 
(
SELECT DISTINCT CourseCompleted AS Course 
FROM StudentDetails 
), 
Students As 
(
SELECT DISTINCT SID, Name 
FROM StudentDetails 
) 

SELECT s.SID, s.name, c.Course AS [Course not Completed] FROM Students s 
CROSS JOIN Courses c 
EXCEPT 
SELECT SID, name, CourseCompleted 
FROM StudentDetails 
ORDER BY s.SID, c.Course 
1
select s.SID, s.Name, c.Course as [Course Not Completed] 
from (select distinct CourseCompleted [Course] from StudentDetails) c, 
StudentDetails s 
where not exists (
    select * from StudentDetails where SID=s.SID and CourseCompleted=c.Course 
) 

当然,如果您有一个列出所有可能课程的表格,您可以用该表格替换from子句中的子查询。