【发布时间】:2013-04-06 05:57:31
【问题描述】:
我在让外连接工作时遇到了一些麻烦:过去我在 MS Access 中让它们按预期工作,但在 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
我可以拉出我想要的列表,但那里没有 NULL 行。再举一个例子,如果我有一个学生的 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
任何帮助都会很棒!
【问题讨论】:
-
在
subquery中也有一个outer join怎么样。你试过了吗?
标签: sql-server outer-join