我想缩短查询的执行时间

时间:2019-07-16 16:11:13

标签: sql-server

我有查询要加载15亿条记录,并且希望缩短执行时间

SELECT TOP (20) a.code AS No_, 
                lastyear =
(
    SELECT SUM(c.[Sales Amount (Actual)])
    FROM [Uneek Clothing Company Ltd$Value Entry] c
    WHERE c.[Source Type] = 1
          AND c.[Global Dimension 1 Code] = a.Code
          AND c.[Source No_] = 'WOR07'
          AND c.[Posting Date] BETWEEN '01/01/2018' AND '7/16/2018'
), 
                CurrentYear =
(
    SELECT SUM(c.[Sales Amount (Actual)])
    FROM [Uneek Clothing Company Ltd$Value Entry] c
    WHERE c.[Source Type] = 1
          AND c.[Global Dimension 1 Code] = a.Code
          AND c.[Source No_] = 'WOR07'
          AND c.[Posting Date] BETWEEN '01/01/2019' AND '7/16/2019'
)
FROM [Uneek Clothing Company Ltd$Item Category] a
ORDER BY CurrentYear DESC;

2 个答案:

答案 0 :(得分:0)

使用要在其中查找数据的字段在表上创建索引。为了提高速度,您可以包括需要参考的货币字段。例如:

CREATE INDEX Idx_SourceType_GlobalDimension1Code_SourceNo_PostingDate
ON [Uneek Clothing Company Ltd$Value Entry] (
    [Source Type], 
    [Global Dimension 1 Code],
    [Source No_],
    [Posting Date]
    )
INCLUDE ([Sales Amount (Actual)])

答案 1 :(得分:0)

我不想偷@Laughing Vergil的雷声,但除了他/她的回答外,我还有一个建议(我没有要评论的排名)。您的索引应创建为使列以降低的特异性排序。我的猜测是您的索引应该看起来像这样,以最大限度地提高性能:

CREATE INDEX Idx_SourceType_GlobalDimension1Code_SourceNo_PostingDate
ON [Uneek Clothing Company Ltd$Value Entry] (
    [Source No_],
    [Posting Date]
    [Global Dimension 1 Code],
    [Source Type], 
)
INCLUDE ([Sales Amount (Actual)])

这假设[Source No_]是另一个表上的唯一键,[Posting Date]是一个日期(漂亮是唯一的),并且代码和类型都非常类似于查找值只有几个不同的可能值。

但是要注意的一点是,该索引是针对该查询专门设计的。如果您从以后的查询中删除[Source No_],则可能还需要创建另一个索引来处理该特定情况。索引维护对于DBA来说是一场持续的战斗,并且有很多聪明的人(aka Brent Ozar)可以帮助您应对这些挑战。