I am looking into ways to optimize the following query which uses a lot of subqueries because they tend to deteriorate the speed of the query. Although the following query works fine, it completes in about 6 seconds which is unacceptable. It searches a table of about 500k customers. Any ideas?
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
)
);