如何加入这两个查询?

时间:2013-05-17 01:31:52

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

此查询会获得多个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的表。

我需要什么?加入表?我不知道现在该做什么。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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
)

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

答案 2 :(得分: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
                    )