SELECT query with CASE condition and SUM()

前端 未结 5 2286
遥遥无期
遥遥无期 2020-12-03 02:59

I\'m currently using these sql statements. My table has the field CPaymentType which contains \"Cash\" or \"Check\". I can sum up the amount of payments by executing 2 SQL s

相关标签:
5条回答
  • 2020-12-03 03:19
    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';
    
    0 讨论(0)
  • 2020-12-03 03:19

    To get each sum in a separate column:

    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';
    
    0 讨论(0)
  • 2020-12-03 03:23

    I don't think you need a case statement. You just need to update your where clause and make sure you have correct parentheses to group the clauses.

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

    The answers posted before mine assume that CDate<=SYSDATETIME() is also appropriate for Cash payment type as well. I think I split mine out so it only looks for that clause for check payments.

    0 讨论(0)
  • 2020-12-03 03:42
    select CPaymentType, sum(CAmount)
    from TableOrderPayment
    where (CPaymentType = 'Cash' and CStatus = 'Active')
    or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
    group by CPaymentType
    

    Cheers -

    0 讨论(0)
  • 2020-12-03 03:43

    Use an "Or"

    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" & "'"
    

    or an "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" & "'"
    
    0 讨论(0)
提交回复
热议问题