2009-11-19 96 views
1

我正在尋找一種方式來優化如下:優化聚集查詢

SELECT 
    (SELECT SUM(amount) FROM Txn_Log WHERE [email protected] AND txnType IN (3, 20)) AS pendingAmount, 
    (SELECT COUNT(1) FROM Txn_Log WHERE gid = @gid AND txnType = 11) AS pendingReturn, 
    (SELECT COUNT(1) FROM Txn_Log WHERE gid = @gid AND txnType = 5) AS pendingBlock 

其中@gid是參數和GID是在這個表上的索引字段。問題:每個子查詢在同一組條目上重新運行 - 三個重新運行是兩個太多。

回答

4

你可以這樣做:

select 
    sum(case when txnType in (3,20) then amount else 0 end) as pendingAmount, 
    sum(case txnType when 11 then 1 else 0 end) as pendingReturn, 
    sum(case txnType when 5 then 1 else 0 end) as pendingBlock 
from 
    Txn_Log 
where 
    gid = @gid 
+1

非常好,您還可以限制txnType IN(3,20,11,5) – 2009-11-19 11:10:03

+0

的初始選擇。同時,對[gid]和[txnType]字段使用索引,甚至可以使用[amount ]以避免查詢甚至查看錶本身。來自[gid],[txnType],[金額]上的覆蓋索引的最大收益, – MatBailie 2009-11-19 11:43:41

1

你能不能做這樣的事

SELECT sum(amount),count(1), txnType 
FROM Txn_log 
WHERE gid = @gid AND 
    txnType in (3,5,11,20) 
group by txnType 

,然後編程方式處理它的休息嗎?