我正在编写一个查询,报告有关某个位置的信息,包括在该位置发生的课程总数以及为这些课程注册的参加者总数。我需要单行的结果。
我正在寻找执行此查询的最有效和/或最易读的方式。
我提出的最干净的查询如下:
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
这种查询在实践中是否可以接受,还是我错过了一些让它更有效的魔法?