如何用聚合函数优化sql查询?

时间:2014-12-16 17:10:56

标签: sql-server

以下是我想要优化的SQL查询。

 SELECT (ISNULL((SELECT SUM(Amount) FROM tblPayment WHERE TransactionType = 1 and AccountType = 2 and Status = 3),0) 
         +
         ISNULL((SELECT SUM(Amount) FROM tblPayment WHERE TransactionType = 2 and AccountType = 2 and Status = 3),0)
        ) 'Total Funds'

如何以更好的方式优化它?

感谢您的任何建议!

2 个答案:

答案 0 :(得分:1)

使用sum TransactionType = 1

而不是对TransactionType = 2TransactionType in (1,2)提出两个不同的查询
SELECT Isnull(Sum(Amount),0)
FROM   tblPayment
WHERE  TransactionType IN( 1, 2 )
       AND AccountType = 2
       AND Status = 3 

答案 1 :(得分:0)

尝试:

SELECT COALESCE(SUM(Amount), 0) AS [Total Funds]
FROM tblPayment
WHERE AccountType = 2 AND Status = 3 
      AND TransactionType IN (1,2)