SQL sum with condition

前端 未结 3 1435
情话喂你
情话喂你 2020-11-30 23:46

I currently have a large SQL statement which i add the following line to in order to get the total cash for each transaction ID (which are unique):

select su         


        
相关标签:
3条回答
  • 2020-11-30 23:50

    With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.

    SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch 
    AND t1.transID = t2.transID
    AND ValueDate > @startMonthDate HAVING money > 0;
    
    0 讨论(0)
  • 2020-11-30 23:55

    Try moving ValueDate:

    select sum(CASE  
                 WHEN ValueDate > @startMonthDate THEN cash 
                  ELSE 0 
               END) 
     from Table a
    where a.branch = p.branch 
      and a.transID = p.transID
    

    (reformatted for clarity)

    You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.

    0 讨论(0)
  • Try this instead:

    SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)
    

    Explanation

    Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

    The CASE expression has two formats:

    • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
    • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

    You want the searched CASE expression syntax:

    CASE
         WHEN Boolean_expression THEN result_expression [ ...n ] 
         [ ELSE else_result_expression ] 
    END
    

    As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

    0 讨论(0)
提交回复
热议问题