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

chr*_*o25 15 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';
Run Code Online (Sandbox Code Playgroud)

Mud*_*san 34

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';
Run Code Online (Sandbox Code Playgroud)


Gal*_*alz 5

要将每个总和放在单独的列中:

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';
Run Code Online (Sandbox Code Playgroud)


sim*_*rcl 5

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

干杯-