このクエリは、必要な結果を提供しますが、実行が非常に遅くなります。速度が遅いのは、[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_