如何提高运行10分钟查询的性能?

时间:2017-05-12 15:51:16

标签: sql sql-server tsql

我有一个查询,大约需要10分钟来执行并生成结果。当我试图将它分解成部分并运行它时,它似乎在几秒钟内运行良好。

我尝试修改查询顶部和底部的子部分,并确定是否导致了问题,但事实并非如此。它在3秒内给出了一些结果。

我正在努力学习阅读Estimated Execution计划,但我越来越难以追查到这个问题。

任何人都可以指出我做出的一些错误,这些错误会导致查询很长时间吗?

Select Distinct
       PostExtended.BatchNum,
       post.ControlNumStatus,
       post.AccountSeg,
       Post.PostDat
From
       Post 
       Post Records 
    join (Select Post, MAX(Dist) as Dist, COUNT(fkglDist) as RecordCount From PostExtend WITH (NOLOCK) Group By flPost) as PostExtender on Post.PK = PostExtender.flPost
    join glPostExtended WITH (NOLOCK) on glPostExtendedLimiter.Post = glPostExtended.Post and (PostExtendedLimiter.fkglDist = PostExtend.Dist or PostExtend.Dist is null)
       join (select lP.fkosControlNumberStatus, lP.SourceJENumber, AccountSegment,
                 sum(case
                    ............
                from Post WITH (NOLOCK)
                  join AccountingPeriod WITH (NOLOCK) on AccountingPeriod.pk = lP.fkglAccountingPeriod
                  join FiscalYear WITH (NOLOCK) on FiscalYear.pk = AccountingPeriod.FiscalYear
                  join Account WITH (NOLOCK) on Account.pk = FiscalYear.Account
                where FiscalYear.Period = @Date
                and glP.fkMLSosCodeEntryType = 2202
                group by glP.fkosControlNumberStatus, glP.SourceNumber, AccountSeg) post on post.ControlNumStatus = Post.fkControlNumberStatus and postdata.SourceJENumber = glPost.SourceJENumber
                where post.AmountT <> 0)......
                Group by

1 个答案:

答案 0 :(得分:1)

子查询通常是问题所在。

我会尝试:

  • postdata 子查询与主查询分开,
  • 将结果保存在临时表中,甚至保存在表变量中,
  • 将聚集索引放在 fkosControlNumberStatus SourceJENumber 字段上,
  • 将此临时表连接回主查询。

有时,这些简单行动的结果令人惊喜。