2013-04-06 95 views
0

讓外部連接工作時遇到了一些麻煩:我已經讓他們按照我以前在MS Access中的預期工作,但在SQL Server中發生類似的事情正在給予我的問題。SQL Server外部連接問題

我有一個適用於每個學生的分數一樣的表:

+-------------+------------+-------+ 
| StudentID | StandardID | Score | 
+-------------+------------+-------+ 
| 100   | 1011  | 1  | 
| 100   | 1012  | 2  | 
| 101   | 1011  | 3  | 

每個學生可能有很多的分數,每個分數與一個標準。此外,每個學生可以屬於一個或多個組,其中包含另一個表內,組:

+-------------+------------+ 
| StudentID | GroupID | 
+-------------+------------+ 
| 100   | 83   | 
| 101   | 83   | 

我想要做的就是提取分數信息,並通過組將其過濾:此數據集將被匹配由StudentID將其提供給其他地方的正確記錄。但是,對於任何給定學生的每個檢索數據集,都需要具有完全相同的行數:每個標準一個。理想的情況是這(對於以上數據):

StudentID = 100 
+------------+-------------+------------+-------+ 
| StandardID | StudentID | GroupID | Score | 
+------------+-------------+------------+-------+ 
| 1011  | 100   | 83   | 1  | 
| 1012  | 100   | 83   | 2  | 

StudentID = 101 
+------------+-------------+------------+-------+ 
| StandardID | StudentID | GroupID | Score | 
+------------+-------------+------------+-------+ 
| 1011  | 101   | 83   | 3  | 
| 1012  | 101   | 83   | NULL | <--Can't get this to happen 

我可以拉起來,我要的名單,但有沒有空行那裏。作爲另一個例子,如果我有一個學生的4個分數,而另一個學生只有1個分數,那麼我仍然需要查詢返回4個行,其中NULL不包含他們的分數。

這是我到目前爲止已經試過(更詳細一點,但在本質上):

SELECT Standards.StandardID, scores.StudentID, scores.TestDate, scores.Score, 
    scores.Assessment 
FROM scores RIGHT OUTER JOIN 
    (SELECT scores_1.StandardID 
    FROM scores AS scores_1 INNER JOIN studentGroups 
     ON scores_1.StudentID = studentGroups.StudentID 
    WHERE (studentGroups.GroupID = 83) 
    GROUP BY scores_1.StandardID) AS Standards 
ON scores.StandardID = Standards.StandardID 
WHERE scores.StudentID = 100 

任何幫助將是驚人的!

+0

如何在子查詢中使用'outer join'。你試過嗎? – 2013-04-06 06:06:24

回答

0

您能爲我們提供數據庫結構嗎?因爲要爲所有學生返回相同數量的行,您需要使用不同的StandardID創建臨時表,然後使用外部聯接爲所有學生獲取相同數量的行。

爲進一步和適當的ans提供表結構。

0

我使用scoresgroups作爲上述兩個表格。你用了更多的術語,所以我得到了(也許)有點困惑。然而,這應該工作:

select AllStandards.StandardID, 
     groups.StudentID, 
     groups.GroupID, 
     Scores.Score 
from (select distinct StandardID from scores) AllStandards 
     left join (
     scores 
     join groups 
      on groups.StudentID = scores.StudentID 
     ) 
     on AllStandards.StandardID = scores.StandardID 
where groups.StudentID=100 

我首先創建的所有可用StandardID列表,然後做一個左連接到所有的學生和成績拿到名單。