2

这个查询有几个AssignmentId's

SELECT AS2.AssignmentId
FROM dbo.AssignmentSummary AS AS2
WHERE AS2.SixweekPosition = 1 AND AS2.TeacherId = 'mggarcia'

此查询仅通过变量获取一个赋值的值@assignmentId

SELECT S.StudentId, 
        CASE WHEN OW.OverwrittenScore IS NOT NULL
            THEN OW.OverwrittenScore
            ELSE dbo.GetFinalScore(S.StudentId, @assignmentId)
        END AS FinalScore
FROM dbo.Students AS S
LEFT JOIN dbo.OverwrittenScores AS OW
    ON S.StudentId = OW.StudentID
    AND OW.AssignmentId = @assignmentId
WHERE S.ClassId IN (
    SELECT C.ClassId
    FROM Classes AS C
    WHERE C.TeacherId = @teacherId
)

正如我所指出的,在最后一个查询中,当您通过变量分配一个值并返回一个表时。现在我想AssignmentId's从第一个查询中得到一个包含几个的表。

我需要什么?连接表?我不知道现在该做什么。

4

3 回答 3

2
AND OW.AssignmentId IN
(
    SELECT AS2.AssignmentId
    FROM   dbo.AssignmentSummary AS AS2
    WHERE  AS2.SixweekPosition = 1 AND AS2.TeacherId = 'mggarcia'
)

如果您能告诉我这些表是如何相互关联的,则可以优化该建议。

于 2013-05-17T01:35:00.357 回答
1

APPLY运算符与相关子查询一起使用。您也可以将 CASE 表达式替换为函数 ISNULL。

SELECT S.StudentId, 
       ISNULL(o.OverwrittenScore, dbo.GetFinalScore(S.StudentId, o.AssignmentId)) AS FinalScore
FROM dbo.Students AS S
  OUTER APPLY (
               SELECT OW.OverwrittenScore, AS2.AssignmentId
               FROM dbo.OverwrittenScores AS OW JOIN dbo.AssignmentSummary AS AS2
                 ON OW.AssignmentId = AS2.AssignmentId
               WHERE AS2.SixweekPosition = 1 AND AS2.TeacherId = 'mggarcia'
                 AND S.StudentId = OW.StudentID
               ) o
WHERE S.ClassId IN (
                    SELECT C.ClassId
                    FROM Classes AS C
                    WHERE C.TeacherId = @teacherId
                    )
于 2013-05-17T07:42:52.993 回答
1

您可以使用以下方法组合它们in

SELECT S.StudentId, 
        CASE WHEN OW.OverwrittenScore IS NOT NULL
            THEN OW.OverwrittenScore
            ELSE dbo.GetFinalScore(S.StudentId, @assignmentId)
        END AS FinalScore
FROM dbo.Students AS S
LEFT JOIN dbo.OverwrittenScores AS OW
    ON S.StudentId = OW.StudentID
    AND OW.AssignmentId in (SELECT AS2.AssignmentId
                            FROM dbo.AssignmentSummary AS AS2
                            WHERE AS2.SixweekPosition = 1 AND AS2.TeacherId = 'mggarcia'
                           )
WHERE S.ClassId IN (
    SELECT C.ClassId
    FROM Classes AS C
    WHERE C.TeacherId = @teacherId
)

可能有一些方法可以简化这个查询。这将第一个查询替换为第二个查询的直接转换。

于 2013-05-17T01:36:55.690 回答