我有这个查询,它给了我需要但执行速度非常慢的结果。缓慢是因为 [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_