2013-04-03 51 views
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') 

請幫助我,在此先感謝。

+0

如何爲您的當前查詢不工作?另外,你應該閱讀數據庫規範化。我發現您的數據構建方式存在一些問題。 –

+0

+1 - 只是爲了擺脫-1,因爲即使這個問題是非常具體的(本地)它仍然很好的結構和足夠的細節 – whytheq

回答

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 
+0

謝謝,這是現在工作:)。 謝謝大家! :) –

+0

@SalikNaqi - 將此標記爲正確的:) – whytheq

1

如果使用SQL Server,我會用

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

這將使學生在任何一個班都獲得A,而不是兩個。 – atw13

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

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