2013-08-26 218 views
0

我有一個Sql Ad-hoc查詢性能很差。請幫我或給我一些建議來優化它。這是下面的查詢:Sql Server 2008 R2查詢優化

SELECT TOP 20 CustomerPrimaryExtID, 
       Max(POSTimeStamp)  AS TransactionDate, 
       ExtLocationCode, 
       0      AS RedemptionAmount, 
       0      AS RedemptionCount, 
       TerminalNum, 
       LogixTransNum, 
       POSTransNum   AS TransNum, 
       0      AS DetailRecords, 
       CustomerTypeID, 
       PresentedCustomerID, 
       PresentedCardTypeID, 
       HHID, 
       Replayed, 
       0      AS TransContext, 
       isnull(TransTotal, 0) AS TransTotal 
FROM TransHist AS TH WITH(nolock) 
WHERE (((CustomerPrimaryExtID IN ('') 
      AND HHID IS NULL) 
      OR HHID = '0000000250000013408' 
       AND CustomerTypeID <> 1) 
      OR (CustomerPrimaryExtID = '0000000250000013408' 
       AND CustomerTypeID = 1)) 
     AND NOT EXISTS (SELECT LogixTransNum 
         FROM TransRedemptionView AS TR2 
         WHERE (((CustomerPrimaryExtID IN ('') 
            AND HHID IS NULL) 
            OR HHID = '0000000250000013408' 
             AND CustomerTypeID <> 1) 
           OR (CustomerPrimaryExtID = '0000000250000013408' 
             AND CustomerTypeID = 1)) 
           AND TH.LogixTransNum = TR2.LogixTransNum) 
GROUP BY CustomerPrimaryExtID, 
      HHID, 
      CustomerTypeID, 
      PresentedCustomerID, 
      PresentedCardTypeID, 
      LogixTransNum, 
      POSTransNum, 
      TerminalNum, 
      ExtLocationCode, 
      Replayed, 
      TransTotal 
ORDER BY TransactionDate DESC 

enter image description here

+0

也許你不需要這麼多的GROUP BY列,也許你只需要最後20個交易...如果是的話,你可以使用行號或連接。 – Justin

+0

這些表中有多少行? –

+0

62%的成本來自我們一無所知的表格。發佈視圖或將查詢轉換爲不使用視圖。 – Paparazzi

回答

0

鑑於TransRedemption我想對CustomerPrimaryExtID,HHID,CustomerTypeID和LogixTransNum指數將有助於一些62%的成本。

你也可以看看這樣做:

FROM 
    TransHist TH 
LEFT OUTER JOIN 
    TransRedemption TR2 
    ON TH.LogixTransNum = TR2.LogixTransNum 

不要使用視圖中的子查詢或加入除非有在該視圖正在做限制的行數從TransRedemption返回。從where子句

AND NOT EXISTS (SELECT LogixTransNum 
        FROM TransRedemptionView AS TR2 
        WHERE (((CustomerPrimaryExtID IN ('') 
           AND HHID IS NULL) 
           OR HHID = '0000000250000013408' 
            AND CustomerTypeID <> 1) 
          OR (CustomerPrimaryExtID = '0000000250000013408' 
            AND CustomerTypeID = 1)) 
          AND TH.LogixTransNum = TR2.LogixTransNum) 

AND TR2.LogixTransNum IS NULL 

取代如果TransRedemption有很多列,那麼你可能要限制在參加像這樣的結果:

然後取出

FROM 
    TransHist TH 
LEFT OUTER JOIN 
    (
     SELECT 
      LogixTransNum 
     FROM 
      TransRedemption 
    ) TR2 
    ON TH.LogixTransNum = TR2.LogixTransNum