案情陈述之和

时间:2019-04-18 07:03:32

标签: sql sql-server-2014

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';

我想对PaymentAmountCheck和PaymentAmountCash求和,有人可以帮助我吗

2 个答案:

答案 0 :(得分:0)

您可以使用以下派生选项添加这两个字段:

SELECT PaymentAmountCheck, 
      PaymentAmountCash, 
      PaymentAmountCheck + PaymentAmountCash AS TotalAmount
FROM (
 Select SUM(IIF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck, 
       SUM(IIF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash,
 from TableOrderPayment 
 where CPaymentType IN ('Check','Cash') and CDate<=SYSDATETIME() and CStatus='Active';
) AS Q;

在SQL Server中,您也可以使用IIF

答案 1 :(得分:0)

由于您在where子句中提到了CPaymentType,因此只需在sum(CAmount)中添加select即可得到PaymentAmountCheckPaymentAmountCash的总和。 / p>

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