2015-12-21 99 views
0

我被要求編寫一個只返回具有特定操作代碼(內部名稱)的帳戶的查詢。有6個代碼必須在帳戶上,並且不能有其他代碼可用。該表存儲在一個名爲tblTrans表(見下文):慢SQL查詢返回 - 如何獲得更好的結果?

AccountNo ActionCode TransactionNo 
1234  Code1  45646453 
1234  Code2  88758475 
1234  Code3  48978978 
1234  Code4  15687898 
1234  Code5  59878988 
1234  Code6  12345677 
2548  Code1  45464533 
2548  Code2  89789489 
2548  Code3  89789781 
2548  Code4  16878983 
2548  Code5  59889884 
2548  Code6  12456776 
2548  Code12  12348887 

因此所需的輸出將只返回帳戶1234

目前這正與查詢做過類似

SELECT AccountNo, ActionCode, TransactionNo  
FROM tblTrans AS t1 
INNER JOIN 
     tblTrans AS t2 ON t1.AccountNo = t2.AccountNo 
     tblTrans AS t3 ON t2.AccountNo = t3.AccountNo 
     tblTrans AS t4 ON t3.AccountNo = t4.AccountNo 
     tblTrans AS t5 ON t4.AccountNo = t5.AccountNo 
     tblTrans AS t6 ON t5.AccountNo = t6.AccountNo 
WHERE t1.ActionCode = 'Code1' 
    AND t2.ActionCode = 'Code2' 
    AND t3.ActionCode = 'Code3' 
    AND t4.ActionCode = 'Code4' 
    AND t5.ActionCode = 'Code5' 
    AND t5.ActionCode = 'Code6' 
    AND t6.AccountNo NOT IN (SELECT ActionCode 
          FROM tblTrans 
          WHERE ActionCode IN ('Code12')) 

對不起,如果語法出來了,我不得不爲了安全原因改變一些細節!

這實際上運行非常緩慢,扼流系統很少。我的問題是,是否有更好的方式來編寫這種類型的查詢。我對CTE的瞭解不多,但聽起來似乎適合?

回答

1

這應該返回AccountNo的只有你想要的代碼。

SELECT AccountNo 
FROM tblTrans 
GROUP BY AccountNo 
HAVING Sum(Case When ActionCode = 'Code1' Then 1 End) > 0 
     And Sum(Case When ActionCode = 'Code2' Then 1 End) > 0 
     And Sum(Case When ActionCode = 'Code3' Then 1 End) > 0 
     And Sum(Case When ActionCode = 'Code4' Then 1 End) > 0 
     And Sum(Case When ActionCode = 'Code5' Then 1 End) > 0 
     And Sum(Case When ActionCode = 'Code6' Then 1 End) > 0 
     And Sum(Case When ActionCode IN ('Code1', 'Code2', 'Code3', 'Code4', 'Code5', 'Code6') Then 0 Else 1 End) = 0 

我修改了查詢。這一個應該表現更好。如果性能仍然不可接受,那麼您應該考慮在表中添加索引。

要恢復所有的數據...

; With FilteredData As 
(
    SELECT AccountNo 
    FROM tblTrans 
    GROUP BY AccountNo 
    HAVING Sum(Case When ActionCode = 'Code1' Then 1 End) > 0 
      And Sum(Case When ActionCode = 'Code2' Then 1 End) > 0 
      And Sum(Case When ActionCode = 'Code3' Then 1 End) > 0 
      And Sum(Case When ActionCode = 'Code4' Then 1 End) > 0 
      And Sum(Case When ActionCode = 'Code5' Then 1 End) > 0 
      And Sum(Case When ActionCode = 'Code6' Then 1 End) > 0 
      And Sum(Case When ActionCode IN ('Code1', 'Code2', 'Code3', 'Code4', 'Code5', 'Code6') Then 0 Else 1 End) = 0 
) 
Select TblTrans.AccountNo, ActionCode, TransactionNumber 
From TblTrans 
     Inner Join FilteredData 
      On tblTrans.AccountNo = FilteredData.AccountNo 
+0

爲什麼認爲,這將有更好的表現? –

+0

此版本比我的第一次嘗試表現更好。我在比較執行計劃的基礎上這樣說。 –

+0

「DISTINCT」是否存在問題? –