我正在寻找一种优化以下方法的方法:
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是此表上的索引字段。问题:每个子查询在同一组条目上重新运行 - 三次重新运行太多了。
答案 0 :(得分: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 :(得分:1)
你能不能做这样的事吗
SELECT sum(amount),count(1), txnType
FROM Txn_log
WHERE gid = @gid AND
txnType in (3,5,11,20)
group by txnType
然后以编程方式处理剩下的部分?