查询多个表并组合结果的有效方法

时间:2019-04-28 19:49:44

标签: performance tsql multiple-tables cross-apply

我正在运行一个查询,以从大约30个表中提取时间序列数据。我正在对数据进行下采样以减少数据点的数量和查询时间。每个表包含数百万行和十几列。我只对几个专栏感兴趣,我计算了移动平均线并向下采样至1小时的增量。但是我看到在添加表时开始有大量时间来运行查询。我希望能够经常运行该更新报告,因此我需要使其运行得更快。

我尝试过的是嵌套派生表和一个“交叉应用”功能,以汇总表中的结果。

是否有更好的方法来减少查询时间?

当前从这3个表中返回735行(15列)。

Select * from
(select
        min([theDate]) as theDate, 
        min([theTime]) as theTime, 
        max([Value]) as maxValue, 
        max([rolling_avg]) as maxDM,
        timeHour as timeHour

from( select [theDate], [theTime], [Value],
       avg(windowAvg) over(order by theDate DESC, theTime rows between 90 preceding and current row) as rolling_avg,
       datepart(hh,theTime) as timeHour
  from (select [theDate], [theTime], [Value], sum([Value]) as windowAvg
          from [Data].[dbo].[tOne]
          Where ([theDate] > convert(DAte,DATEADD(month, -1, GETDATE())))
          group by theDate, theTime, Value 

          )tOneTemp   
          )tOneTempTwo
          group by theDate, timeHour) tOne 
Cross Apply (select
        min([theDate]) as theDate, 
        min([theTime]) as theTime, 
        max([Value]) as maxValue, 
        max([rolling_avg]) as maxDM,
        timeHour as timeHour

from( select [theDate], [theTime], [Value],
       avg(windowAvg) over(order by theDate DESC, theTime rows between 90 preceding and current row) as rolling_avg,
       datepart(hh,theTime) as timeHour
  from (select [theDate], [theTime], [Value], sum([Value]) as windowAvg
          from [Data].[dbo].[tTwo]
          Where ([theDate] > convert(DAte,DATEADD(month, -1, GETDATE())))
          group by theDate, theTime, Value 

          )tTwoTemp   
          )tTwoTempTwo
          group by theDate, timeHour) tTwo

Cross Apply (select
        min([theDate]) as theDate, 
        min([theTime]) as theTime, 
        max([Value]) as maxValue, 
        max([rolling_avg]) as maxDM,
        timeHour as timeHour

from( select [theDate], [theTime], [Value],
       avg(windowAvg) over(order by theDate DESC, theTime rows between 90 preceding and current row) as rolling_avg,
       datepart(hh,theTime) as timeHour
  from (select [theDate], [theTime], [Value], sum([Value]) as windowAvg
          from [Data].[dbo].[tThree]
          Where ([theDate] > convert(DAte,DATEADD(month, -1, GETDATE())))
          group by theDate, theTime, Value 

          )tThreeTemp   
          )tThreeTempTwo
          group by theDate, timeHour) tThree

where tOne.timeHour = tTwo.timeHour and tOne.theDate = tTwo.theDate and tOne.timeHour = tThree.timeHour and tOne.theDate = tThree.theDate
 order by tOne.theDate DESC, tOne.theTime DESC  

0 个答案:

没有答案