0

我在让外部连接工作时遇到了一些麻烦:过去我已经让它们按预期在 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

任何帮助都会很棒!

4

2 回答 2

0

你能给我们提供数据库结构吗因为要为所有学生返回相同数量的行,你需要创建一个具有不同 StandardID 的临时表,然后使用外连接为所有学生获取相同数量的行。

为进一步和适当的ans提供表格结构。

于 2013-04-06T06:25:01.017 回答
0

我使用scoresandgroups作为上面描述的两个表。你使用了更多的术语,所以我(也许是)有点困惑。但是,这应该有效:

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然后对所有学生和分数进行左连接以获得列表。

于 2013-04-06T08:40:17.453 回答