我有这个查询,它给了我需要的结果,但执行速度非常慢。缓慢是因为[Contoso $ Item Ledger Entry]表有~0.6M的记录。 请建议如何优化/简化此查询(如果可能)以及我需要具备哪些索引以使其最佳运行。
DECLARE @TempTable TABLE
(
Numeris varchar(20)
)
INSERT INTO @TempTable (Numeris)
SELECT No_
FROM [Contoso$Sales Line]
WHERE [Document no_] = 'PP03428'
SELECT I.No_, CASE WHEN
ISNULL(ROUND(CAST(SUM(ILE.[Remaining Quantity]) AS float), 2), 0) <
(SELECT ISNULL(SUM([Outstanding Quantity]), 0)
FROM [Contoso$Sales Line] SL
WHERE (SL.No_ = I.No_)
AND (SL.[Document type] = 1 OR SL.[Document type] = 2)
AND (SL.[DA4 eksportas] = 0)
AND (SL.Type = 2)
)
THEN 0
ELSE
ISNULL(ROUND(CAST(SUM(ILE.[Remaining Quantity]) AS float), 2) -
(SELECT ISNULL(SUM([Outstanding Quantity]), 0)
FROM [Contoso$Sales Line] SL
WHERE (SL.No_ = I.No_)
AND (SL.[Document type] = 1 OR SL.[Document type] = 2)
AND (SL.[DA4 eksportas] = 0)
AND (SL.Type = 2)), 0
)
END AS Kiekis
FROM [Contoso$Item] I
LEFT OUTER JOIN [Contoso$Item Ledger Entry] ILE ON I.No_ = ILE.[Item No_]
WHERE I.No_ IN (SELECT Numeris FROM @TempTable)
GROUP BY I.No_
答案 0 :(得分:0)
使用执行计划了解查询的执行方式,并了解查询速度如此之慢的原因。您可以在Contoso $ Item表的No_ Column上添加索引,以避免使用fullscan表