【问题标题】:SQL Server outer join issueSQL Server 外连接问题
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多