2013-04-06 71 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列表,然后做一个左连接到所有的学生和成绩拿到名单。