如何看待课程成绩之间的相互关系?

时间:2013-04-03 15:59:02

标签: sql sql-server

我是SQL Server新手。请帮我找到两门课程的成绩之间的相互关系。

我想找到哪个学生在'计算机程序设计'中获得'A'成绩,他在计算机概论中也有'A'等级。

这就是数据的样子:

RollNum | CGPA | Status     | Name                              | Grade
410     | 2.6  | Completed  | Introduction to Computer Science  | A  
410     | 2.6  | Completed  | Computer Programming              | A-  
422     | 3.2  | Completed  | Introduction to Computer Science  | A 
422     | 3.2  | Completed  | Computer Programming              | A  
223     | 3.52 | Completed  | Introduction to Computer Science  | A 
223     | 3.52 | Completed  | Computer Programming              | A 
521     | 1.2  | Completed  | Introduction to Computer Science  | B+ 
521     | 1.2  | Completed  | Computer Programming              | A-
....
....  

这是我正在写的查询:

SELECT [RollNum],[CGPA],[Status],[Name],[FinalGrade]
 FROM db
     where Name ='Introduction to Computer Science' and FinalGrade='A' 
  and (Name='Computer Programming' and FinalGrade= 'A' )

请帮助我,先谢谢。

3 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

select RollNum
from db
where [Name] in ('Introduction to Computer Science', 'Computer Programming')
  and [Grade] = 'A'
group by RollNum
having count(distinct name) = 2

这称为Relational Division,将返回学生RollNum,他们在这两个课程中都获得了A。{/ p>

请参阅SQL Fiddle with Demo

如果您想要的不仅仅是RollNum,那么您可以在WHERE EXISTS中使用上述查询:

select [RollNum], [CGPA], [Status], [Name], [Grade]
from db d1
where exists (select RollNum
              from db d2
              where [Name] in ('Introduction to Computer Science', 'Computer Programming')
                and [Grade] = 'A'
                and d1.rollnum = d2.rollnum
              group by RollNum
              having count(distinct name) = 2);

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

如果使用SQL服务器,我会使用

Select [RollNum],[CGPA],[Status],[Name],[FinalGrade]
from db
where [Name] in ('Introduction to Computer Science', 'Computer Programming')
and [FinalGrade] = 'A'

答案 2 :(得分:1)

SELECT qCP.*
FROM (SELECT RollNum, CGPA, Status, Name, FinalGrade
      FROM db
      WHERE Name = 'Computer Programming' 
      AND FinalGrade = 'A') qCP
INNER JOIN 
    (SELECT RollNum 
     FROM db 
     WHERE Name = 'Introduction to Computer Science' 
     AND FinalGrade = 'A') qIntro
ON qCP.RollNum = qIntro.RollNum