- 为什么在这个查询中,需要最后一个“WHERE”子句来限制重复项?
- 第一个 LEFT JOIN 是将程序链接到 UID 上的实体
- 第一个 INNER JOIN 是将程序链接到子查询,该子查询通过链接 UID 来获取这些程序的统计信息
- 子查询(获取 StatsForDistributorClubs 子集)正在对 UID 列进行分组
- 所以,我本以为无论如何这都会加入唯一记录,所以我们不应该得到重复行
- 那么为什么需要通过确保“程序”链接到“实体”来基于最终的 WHERE 进行限制呢?
(为清楚起见,省略了查询的无关部分)
SELECT LmiEntity.[DisplayName]
,StatsForDistributorClubs.*
FROM [Program]
LEFT JOIN
LMIEntityProgram
ON LMIEntityProgram.ProgramUid = Program.ProgramUid
INNER JOIN
(
SELECT e.LmiEntityUid,
sp.ProgramUid,
SUM(attendeecount) [Total attendance],
FROM LMIEntity e,
Timetable t,
TimetableOccurrence [to],
ScheduledProgramOccurrence spo,
ScheduledProgram sp
WHERE
t.LicenseeUid = e.lmientityUid
AND [to].TimetableOccurrenceUid = spo.TimetableOccurrenceUid
AND sp.ScheduledProgramUid = spo.ScheduledProgramUid
GROUP BY e.lmientityUid, sp.ProgramUid
) AS StatsForDistributorClubs
ON Program.ProgramUid = StatsForDistributorClubs.ProgramUid
INNER JOIN LmiEntity
ON LmiEntity.LmiEntityUid = StatsForDistributorClubs.LmiEntityUid
LEFT OUTER JOIN Region
ON Region.RegionId = LMIEntity.RegionId
WHERE (
[Program].LicenseeUid = LmiEntity.LmiEntityUid
OR
[LMIEntityProgram].LMIEntityUid = LmiEntity.LmiEntityUid
)