使用CASE条件和SUM()的SELECT查询

时间:2014-01-05 15:18:31

标签: sql sql-server sum case conditional-statements

我目前正在使用这些sql语句。我的表有CPaymentType字段,其中包含“Cash”或“Check”。我可以通过执行2个SQL语句来总结支付金额,如下所示。在这种情况下,用户甚至不会注意到执行2个sql语句时的速度差异或只是1,但是,我不喜欢我的方式,我只想要1个sql语句。如何使用CASE条件将这些重构为1个语句?我无法弄明白,因为在线示例导致1或0或布尔值。我不希望包含过期的支票付款。非常感谢你。

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType='Cash' and CStatus='Active';

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType='Check' and CDate<=SYSDATETIME() and CStatus='Active';

5 个答案:

答案 0 :(得分:24)

Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
       SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';

答案 1 :(得分:4)

select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType

干杯 -

答案 2 :(得分:2)

要在单独的列中获取每笔金额:

Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CDate<=SYSDATETIME() 
and CStatus='Active';

答案 3 :(得分:0)

使用“或”

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

或“IN”

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

答案 4 :(得分:0)

我认为你不需要个案陈述。您只需更新where子句并确保使用正确的括号对子句进行分组。

SELECT Sum(CAMount) as PaymentAmount 
from TableOrderPayment 
where (CStatus = 'Active' AND CPaymentType = 'Cash') 
OR (CStatus = 'Active' and CPaymentType = 'Check' and CDate<=SYSDATETIME())

我之前发布的答案假设CDate&lt; = SYSDATETIME()也适用于现金支付类型。我想我把我分开了,所以它只查找支票付款条款。

相关问题