0

我是 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' )

请帮助我,在此先感谢。

4

3 回答 3

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

这被称为关系部门,并将返回RollNum他们参加两个课程并A在每个课程中获得的学生。

请参阅带有演示的 SQL Fiddle

如果您想要的不仅仅是RollNum,那么您可以在 a 中使用上述查询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

于 2013-04-03T16:04:50.620 回答
1

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

Select [RollNum],[CGPA],[Status],[Name],[FinalGrade]
from db
where [Name] in ('Introduction to Computer Science', 'Computer Programming')
and [FinalGrade] = 'A'
于 2013-04-03T16:03:28.200 回答
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
于 2013-04-03T16:05:10.080 回答