Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SUMMING a conditional statement

Tags:

sql

mysql

I have the following query that gives me the sum of sales:

SELECT SUM(sales)
FROM 
    (SELECT sales FROM ...) combined

I now need to add a conditional subtraction based upon certain currencies that take out taxes, something like this, in pseudocode:

SELECT SUM(sales) - (SUM(sales) IF currency IN ('jpy', 'aud') * 0.05)
FROM 
    (SELECT sales FROM ...) combined

How would I create this conditional SUM or subquery?

like image 889
David542 Avatar asked Jun 03 '12 19:06

David542


1 Answers

You might apply factor while summing:

SELECT SUM(CASE WHEN currency IN ('jpy', 'aud') 
                THEN sales * 0.95
                ELSE sales
            END)
FROM combined

CASE has two forms. This one checks whether boolean expression given after WHEN evaluates to true. If it does, it returns sales scaled down by 5 percent; if it does not, returns expression after ELSE. You can combine WHEN...THEN pairs. The first one that evaluates to true returns expression after THEN.

You might have done this as you suggested in a question, by substracting TAX from JPY and AUD, as follows:

SELECT SUM(sales) 
     - ifnull (SUM(CASE WHEN currency IN ('jpy', 'aud') 
                        THEN sales * 0.05
                    END), 0)
FROM combined

But it would not help the query in any way.

like image 57
Nikola Markovinović Avatar answered Sep 28 '22 01:09

Nikola Markovinović