クエリの速度が低下する傾向があるため、多くのサブクエリを使用する次のクエリを最適化する方法を検討しています。次のクエリは問題なく動作しますが、許容できない約 6 秒で完了します。約 50 万人の顧客のテーブルを検索します。何か案は?
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
)
);