SQL sum with condition

Sql

Sql Problem Overview


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 sum(cash) from Table a where a.branch = p.branch 
and a.transID = p.transID) TotalCash

and i now need to do the same but only total the cash values that have a valuedate within the last month, so i have something like this:

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

Sorry that I dont have the whole statement, but it is really long and specific to the context of the stored procedure but was hoping someone would know what i mean?

Sql Solutions


Solution 1 - Sql

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.

Solution 2 - Sql

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.

Solution 3 - Sql

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGraceView Question on Stackoverflow
Solution 1 - SqlMark ByersView Answer on Stackoverflow
Solution 2 - SqlJames WisemanView Answer on Stackoverflow
Solution 3 - SqlJonathan Cedrim De SouzaView Answer on Stackoverflow