查询优化

时间:2013-12-06 09:34:29

标签: sql sql-server optimization

我有一张包含所有销售记录的表格(按文件/项目)。 我需要一个包含一些指标的报告,但仅适用于VB文档(文档类型)。但是我需要一些指标,例如每天/项目的最大数量,这会迫使我进行另一次查询,但这会按天分组。 问题是我得到一个非常慢的查询。总共4700000次查询占用了4h。

是否可以优化此查询?可能不是最好的方式......

SELECT std.ItemID AS [REF.], SUM(std.Quantity) AS [TOTAL QTY]
, MAX(t1.Qty) AS [MAX QTY BY DAY]
, COUNT(DISTINCT(std.CreateDate)) AS [SALES DAYS]
, DATEDIFF(DAY,MIN(std.CreateDate),MAX(std.CreateDate))+1 AS [CALENDAR DAYS]
FROM SaleTransactionDetails std
INNER JOIN (
    SELECT CreateDate, ItemID, SUM(Quantity) AS [Qty]
    FROM SaleTransactionDetails
    WHERE TransDocument = 'VB' AND CreateDate > '2012-12-15'
    GROUP BY CreateDate, ItemID) t1 
    ON std.ItemID = t1.ItemID
WHERE std.TransDocument = 'VB' AND std.CreateDate > '2012-12-15'
GROUP BY std.ItemID

我会感激任何帮助。谢谢大家!

1 个答案:

答案 0 :(得分:1)

您不需要两次引用该表来执行此操作,您可以从一次扫描中获得所需的一切:

SELECT  [REF.] = std.ItemID,
        [Total Quantity] = SUM(std.Quantity),
        [Max Qty By Day] = MAX(std.Quantity),
        [Sales Days] = COUNT(std.CreateDate),
        [Calendar Days] = DATEDIFF(DAY, MIN(std.CreateDate), MAX(std.CreateDate)) + 1
FROM    (   SELECT  std.CreateDate,
                    std.ItemID,
                    Quantity = SUM(std.Quantity)
            FROM    SaleTransactionDetails std
            WHERE   std.TransDocument = 'VB' 
            AND     std.CreateDate > '2012-12-15'
            GROUP BY std.CreateDate, std.ItemID
        ) std
GROUP BY std.ItemID;

但是,您的性能中更重要的因素将是表的索引方式。找出所需索引的最佳方法是在启用“显示实际执行计划”选项的情况下运行查询,然后SSMS将建议索引以改进查询。我猜想以下filtered index会提高性能

CREATE NONCLUSTERED INDEX IX_SaleTransactionDetails_ItemID_CreateDate
    ON SaleTransactionDetails (ItemID, CreateDate)
    INCLUDE (Quantity)
    WHERE TransDocument = 'VB';