在这个场景中有四个表:TableA、TableB 和 TableC、TableD 和 TableE
TableA -> TableB = 1-to-many
TableB -> TableC = 1-to-many
TableB -> TableD = 1-to-1
TableC -> TableE = 1-to-1
TableA { Id (PK), Field1 (float), DateField (DateTime) }
TableB { Id (PK), TableAId (FK), TableDId (FK), Field2 (float) }
TableC { Id (PK), TableBId (FK), TableEId (FK), Field3 (float) }
TableD { Id (PK), Type (tinyint) }
TableE { Id (PK), Type (tinyint) }
TableB 中的一些(但不是所有)记录包含 TableC 中的子记录。基于一些 DateRange (from-to),我需要从 TableA 及其相关记录中获取所有记录,并计算:
- TableA.Field1 的摘要,
- TableB.Field2 的摘要,按 TableD.Type 分组(有 5 种不同的类型)。
- TableC.Field3 的摘要,由 TableE.Type 组成(有 4 种不同的类型)。
因此,结果应包含 10 个计算摘要。实现这一目标的最有效方法是什么?
编辑:这里是伪查询作为每个摘要的示例:
SELECT SUM(a.Field1) FROM TableA a INNER JOIN TableB b ON a.Id = b.TableAId WHERE a.DateField BETWEEN DateFrom AND DateTo
SELECT SUM(b.Field2) FROM TableA a INNER JOIN TableB b ON a.Id = TableD d ON b.TableDId=d.Id WHERE a.DateField BETWEEN DateFrom AND DateTo AND d.Type = 1
SELECT SUM(b.Field2) FROM TableA a INNER JOIN TableB b ON a.Id = TableD d ON b.TableDId=d.Id WHERE a.DateField BETWEEN DateFrom AND DateTo AND d.Type = 2 // etc to 5
SELECT SUM(c.Field3) FROM TableA a INNER JOIN TableB b ON a.Id = b.TableAId INNER JOIN TableC c ON b.Id=c.TableBId INNER JOIN TableE ON c.TableEId=e.Id WHERE a.DateField BETWEEN DateFrom AND DateTo AND e.Type = 1 // 3x this query, only type is different