如何合并这两个查询

时间:2016-01-06 10:35:00

标签: sql sql-server database sql-server-2012 query-optimization

我需要将这两个查询合并到一个查询中。

首先查询:

sSQLO = " SET NOCOUNT ON " & _
        " SELECT TOP 1 dbo.tblScheduleExaminees.formAdministerID, dbo.tblBatteryToExams.testOrder, " & _
        " dbo.tblScheduleExaminees.takenNumber " & _
        " FROM dbo.tblScheduleExaminees WITH (NOLOCK) " & _
        " INNER JOIN dbo.tblBatteryToExams WITH (NOLOCK) ON (dbo.tblBatteryToExams.schID = dbo.tblScheduleExaminees.schID) " & _
        " INNER JOIN dbo.tblBattery WITH (NOLOCK) ON ((dbo.tblBattery.batteryID = dbo.tblBatteryToExams.batteryID) AND (dbo.tblBattery.isDeleted  = 0) AND (dbo.tblBattery.isExpired = 0)) " & _
        " WHERE dbo.tblScheduleExaminees.isDeleted = 0 " & _
        "   AND dbo.tblScheduleExaminees.examineeID = " & pExamineeID & _
        "   AND dbo.tblScheduleExaminees.areaOption = " & iAreaID & _
        "   AND dbo.tblScheduleExaminees.confirmCheckIn = 1 " & _
        " ORDER BY dbo.tblScheduleExaminees.takenNumber DESC " & _
        " SET NOCOUNT OFF "

第二次查询:

sSQLC = " SET NOCOUNT ON  " & _
        " SELECT TOP 1 dbo.tblScheduleExaminees.areaOption " & _
        " FROM dbo.tblScheduleExaminees WITH (NOLOCK) " & _
        " INNER JOIN dbo.tblBatteryToExams WITH (NOLOCK) ON dbo.tblBatteryToExams.schID = dbo.tblScheduleExaminees.schID " & _
        " AND dbo.tblBatteryToExams.ssScore = '' " & _
        " INNER JOIN dbo.tblBattery WITH (NOLOCK) ON ((dbo.tblBattery.batteryID = dbo.tblBatteryToExams.batteryID) AND (dbo.tblBattery.isDeleted  = 0) AND (dbo.tblBattery.isExpired = 0)) " & _
        " WHERE dbo.tblScheduleExaminees.examineeID = " & pExamineeID & _
        "   AND dbo.tblScheduleExaminees.areaOption = " & iAreaID & _
        "   AND dbo.tblScheduleExaminees.takenNumber = " & iTakenNumber & _
        "   AND dbo.tblScheduleExaminees.isDeleted = 0 " & _
        "   AND dbo.tblScheduleExaminees.confirmCheckIn IN (0,1) " & _
        " ORDER BY dbo.tblScheduleExaminees.checkInDate DESC " & _
        " SET NOCOUNT OFF "

这些查询完全相同。第一个查询SELECT-ed的dbo.tblScheduleExaminees.takenNumber由第二个查询使用,名称为iTakenNumber

1 个答案:

答案 0 :(得分:1)

SELECT TOP (1) e.areaOption
FROM (
    SELECT
          e.areaOption
        , e.takenNumber
        , be.ssScore
        , e.checkInDate
        , MaxTakenNumber = MAX(CASE WHEN e.confirmCheckIn = 1 THEN takenNumber END) OVER (ORDER BY takenNumber DESC)
    FROM dbo.tblScheduleExaminees e
    JOIN dbo.tblBatteryToExams be ON be.schID = e.schID
    WHERE e.examineeID = @pExamineeID
        AND e.areaOption = @iAreaID
        AND e.isDeleted = 0
        AND e.confirmCheckIn IN (0, 1)
        AND EXISTS(
                SELECT 1
                FROM dbo.tblBattery b
                WHERE b.batteryID = be.batteryID
                    AND b.isDeleted = 0
                    AND b.isExpired = 0
            )
) t
WHERE t.MaxTakenNumber = t.takenNumber
    AND t.ssScore = ''
ORDER BY t.checkInDate DESC