选择项目数和这些项目的所有子项数

时间:2013-08-01 19:54:27

标签: sql performance aggregate

我正在撰写一个报告,报告有关某个位置的信息,包括该位置发生的课程总数以及为这些课程注册的与会者总数。我需要将结果放在一行中。

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

我提出的最清晰的查询如下:

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

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

1 个答案:

答案 0 :(得分: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...