Sum of Two Columns Only When One Column Has A Certain Value

  • Dear Forum:

    I have two columns (Col3 and Col4).  I need a SUM of these two columns, but only when Col2 > 0.

    I cannot add in the WHERE clause WHEN COL2 > 0, because I need to use this column elsewhere in my query and cannot limit it for the entire query.  I just need for one column in my recordset to only do a SUM when the value is greater than zero.   My thought being a subquery inside the main query, but not sure if this is the most efficient way to handle this.

     

  • If you're adding one column to another, like [column A] + [column B], you can use

    CASE WHEN [some column] = 0 THEN <true part> ELSE <false part> END

    where the True Part and False part can be expressions. Then you can sum that.

  • What is the difference between this question and the one pasted here?

    https://www.sqlservercentral.com/forums/topic/sum-of-column-when-values-different

    Michael L John
    If you assassinate a DBA, would you pull a trigger?
    To properly post on a forum:
    http://www.sqlservercentral.com/articles/61537/

  • The easy answer is that I didn't understand them to be the same and/or related.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply