-1

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
)
);
4

2 回答 2

1

考虑添加缓存表,您已经为客户预先计算了所有借方、贷方、借方结算和贷方结算。我假设事务表永远不会更新,只在插入后插入如此简单的触发器来执行计算。

CREATE TABLE Balance
(
    CustomerID int NOT NULL,
    Debit decimal(18, 2) NOT NULL,
    Credit decimal(18, 2) NOT NULL,
    DebitSettlement decimal(18, 2) NOT NULL,
    CreditSettlement decimal(18, 2) NOT NULL
)

CREATE TRIGGER CalculateBalance
ON [Transaction]
 AFTER INSERT,UPDATE
AS
DECLARE @CustomerID int

SET @CustomerID = (SELECT customerID FROM inserted)

-- Calculate Debit, Credit, DebitSettlement and CreditSettlement for current customer

GO
于 2013-06-13T11:01:09.857 回答
0

尝试为查询制定执行计划,它还提供有关查询滞后位置的建议,还尝试在您使用查询的表的字段上创建索引。

于 2013-06-13T10:31:57.137 回答