1

我正在寻找一种优化以下内容的方法:

SELECT 
    (SELECT SUM(amount) FROM Txn_Log WHERE gid=@gid 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

2 回答 2

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
于 2009-11-19T11:08:23.617 回答
1

你能不能不做这样的事情

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

然后以编程方式处理其余部分?

于 2009-11-19T11:09:49.713 回答