0

在这个场景中有四个表: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
4

1 回答 1

0

我认为这里最好的方法是用 CTE 将整个事情写在一个查询中,让 SQL Server 的优化器找出执行这个事情的最佳方法。这样我们就不会:

  1. 重复处理多个查询
  2. 创建未索引的表变量
  3. 创建需要写入磁盘的临时表

这是查询:

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
于 2013-06-21T03:49:06.363 回答