0

我正在编写一个查询,报告有关某个位置的信息,包括在该位置发生的课程总数以及为这些课程注册的参加者总数。我需要单行的结果。

我正在寻找执行此查询的最有效和/或最易读的方式。

我提出的最干净的查询如下:

SELECT Location.Id AS LocationId,
       --additional columns from location or joined tables...
       ClassStatistics.TotalClasses,
       ClassStatistics.TotalRegistrants
FROM Locations AS Location
OUTER APPLY
    (
        SELECT
            COUNT(*) AS TotalClasses,
            SUM(TotalRegistrantsInClass) AS TotalRegistrants
        FROM 
            (
                SELECT 
                    Class.Id AS ClassId,
                    COUNT(*) AS TotalRegistrantsInClass
                FROM
                    Classes AS Class
                    LEFT OUTER JOIN
                        Attendees AS Attendee
                    ON 
                        Attendee.ClassId = Class.Id
                WHERE
                    Class.LocationId= Location.Id
                GROUP BY
                    Class.Id
            ) AS AttendeeTotalsByClass
    ) AS ClassStatistics
WHERE
    Location.Id = 1

这种查询在实践中是否可以接受,还是我错过了一些让它更有效的魔法?

4

1 回答 1

0

您应该直接加入 Classes 和 Attendee 表。不需要所有的子查询。

SELECT  Location.Id AS LocationId,
        --additional columns from location or joined tables...
        COUNT(DISTINCT C.ID) AS TotalClasses,
        COUNT(A.ID) AS TotalRegistrants
FROM    Locations AS L
INNER JOIN
        CLASSES C
ON      C.LocationId= L.Id      
LEFT OUTER JOIN
        Attendees A
ON      A.ClassId = C.Id       
WHERE   L.Id = 1
GROUP BY
        Location.Id AS LocationId,
        --additional columns from location or joined tables...
于 2013-08-01T20:33:24.870 回答