在这种情况下,有四个表: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中获取所有记录及其相关记录,并计算:
因此,结果应包含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
答案 0 :(得分:0)
我认为这里最好的方法是使用CTE在一个查询中编写整个内容,让SQL Server的优化器找出执行此操作的最佳方法。这样我们就不会:
以下是查询:
with a as (select * from tableA where datefield between datefrom and dateto),
b as ( select * from tableB where tableB.tableAid = a.id)
select null, sum(a.field1) from a
union
select d.type, sum(b.field2)
from b
join tableD d on d.id = b.tableDid
group by d.type
union
select e.type, sum(c.field3)
from tableC c
join b on b.id = c.tableBid
join tableE e on e.id = c.tableEid