如何通过运行总计加快选择查询的速度?

时间:2019-05-10 00:32:09

标签: sql sql-server

我有一个约有45,000行的源表。它包含一些详细信息,然后是一个星期编号,以及该周的计划数量和已发货数量以及详细信息。我现在正在尝试为计划中的和已发货的添加运行数量

我编写了一个查询,如果添加许多WHERE子句,该查询将起作用,但是如果删除它们,该查询将运行很长时间。

SELECT

 s.Season
,s.CustomerCode
,s.Customer
,s.VarietyCode
,s.Variety
,s.GrowingMethodCode
,s.ProductSizeCode
,s.PackType
,s.Market
,s.Brand
,s.WeekNum
,s.Qty_Planned
,(SELECT

  SUM(Qty_Planned)

  FROM  [DataMiningImports].[Apples_Planned_vs_Shipped]
  WHERE WeekNum <= s.WeekNum
  AND   Season = s.Season
  AND   CustomerCode = s.CustomerCode
  AND   VarietyCode = s.VarietyCode
  AND   GrowingMethodCode = s.GrowingMethodCode
  AND   ProductSizeCode = s.ProductSizeCode
  AND   PackType = s.PackType
  AND   Market = S.Market
  AND   Brand = s.Brand
  ) AS Qty_Planned_Running

,s.Qty_Shipped

,(SELECT

  SUM(Qty_Shipped)

  FROM  [DataMiningImports].[Apples_Planned_vs_Shipped]
  WHERE WeekNum <= s.WeekNum
  AND   Season = s.Season
  AND   CustomerCode = s.CustomerCode
  AND   VarietyCode = s.VarietyCode
  AND   GrowingMethodCode = s.GrowingMethodCode
  AND   ProductSizeCode = s.ProductSizeCode
  AND   PackType = s.PackType
  AND   Market = S.Market
  AND   Brand = s.Brand
  ) AS Qty_Shipped_Running

FROM [DataMiningImports].[Apples_Planned_vs_Shipped] AS s

ORDER BY S.WeekNum

1 个答案:

答案 0 :(得分:2)

您正在子查询中求和,最有可能针对外部表中的每一行运行一次。

相反,请尝试使用窗口函数:

SELECT Season, 
       CustomerCode, Customer,
       VarietyCode, Variety,
       GrowingMethodCode, ProductSizeCode, PackType, Market, Brand, 
       WeekNum, Qty_Planned, 
       SUM(Qty_Planned) OVER(PARTITION BY Season, CustomerCode, VarietyCode, GrowingMethodCode, ProductSizeCode, PackType, Market, Brand ORDER BY WeekNum) AS Qty_Planned_Running, 
       SUM(Qty_Shipped) OVER(PARTITION BY Season, CustomerCode, VarietyCode, GrowingMethodCode, ProductSizeCode, PackType, Market, Brand ORDER BY WeekNum) AS Qty_Shipped_Running
FROM [DataMiningImports].[Apples_Planned_vs_Shipped]
ORDER BY WeekNum