我正在研究如何優化以下使用大量子查詢的查詢,因爲它們往往會降低查詢的速度。雖然下面的查詢工作正常,但它在大約6秒內完成,這是不可接受的。它搜索一個約500k客戶的表格。有任何想法嗎?優化使用多個子查詢編寫的查詢
SELECT (
(SELECT coalesce(SUM(cashout),0)-
((select coalesce(sum(Buyin),0) from [Transaction] where TYPE='Credit' and CustomerID=132)
+ (select coalesce(sum(Paid),0) from [Transaction] where TYPE='Credit' and CustomerID=132))
FROM [transaction]
WHERE TYPE='Credit'
AND CustomerID=132
)
-------------------
+
(
(SELECT coalesce(SUM(cashout),0)
- (select coalesce(sum(Paid),0) from [Transaction] where TYPE='Debit' AND Cashout>buyin and CustomerID=132)
+ (select coalesce(sum(Cashout),0)- (select coalesce(sum(PAID),0) from [Transaction] where TYPE='Debit' AND Cashout<buyin and CustomerID=132)
from [Transaction] where TYPE='Debit' AND Cashout<Buyin and CustomerID=132)
+ (select coalesce(sum(Cashout),0)- (select coalesce(sum(PAID),0) from [Transaction] where TYPE='Debit' AND Cashout=buyin and CustomerID=132)
from [Transaction] where TYPE='Debit' AND Cashout=Buyin and CustomerID=132)
FROM [Transaction]
WHERE CustomerID=132
AND TYPE='Debit'
AND Cashout>buyin)
)
--------------
-
(
select coalesce(sum(Paid),0)
from [Transaction]
where type='Debit Settlement'
AND CustomerID =132
)
--------------
+
(
select coalesce(sum(Paid),0)
from [Transaction]
where type='Credit Settlement'
AND CustomerID =132
)
);
你也許可以將所有的這些成一個主查詢和擺脫子查詢與例如'SELECT和'等等(當類型=「信用結算」 AND客戶id = 132 THEN付費END CASE) 。 –
謝謝!這也有幫助。 @MartinSmith –