Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing sum's if certain conditions are true

Tags:

mysql

I am trying to build a query that does a sum if a certain parameter is set. For example:

SELECT SUM(IF(<condition>,field,field)) AS total_value

...which is working correctly.

But i have more than one condition in the IF(), like:

SELECT SUM(IF(<condition> <condition>,field,field)) AS total_value

..which is not working, could you have any idea what should be the right query for this.

Update

Sorry for wrong queries, right queries are

My current query looks something like this: SELECT SUM(IF(condition1,field,field)) AS total_value which is working correctly.

But i have more than one condition in IF(),like SELECT SUM(IF(condition1 condition2,field,field)) AS total_value which is not working, could you have any idea what should be the right query for this.

like image 525
Gugu Avatar asked Jun 11 '10 15:06

Gugu


2 Answers

Look at the Case statement:

Select Sum( Case When column = test Then column2 Else column3 End )
...

If you have multiple conditions, you can still use case:

Select Sum( Case 
            When column1 = 'Foo' Then column2 
            When column1 = 'Bar' Then column3
            When column1 = 'Gamma' Then column2 + column3
            Else column3 End )
From ...

In this scenario, if column1 is not null and does not equal 'Foo', then it will go to the next When statement. If that test is not true, it goes to the next and so on.

like image 92
Thomas Avatar answered Oct 13 '22 00:10

Thomas


select sum(case when a = b and x = y then field1 + field2 else 0 end)

Update:

Perhaps you mean this:

select sum(case when a = b then field1 else field2 end)
like image 27
D'Arcy Rittich Avatar answered Oct 13 '22 00:10

D'Arcy Rittich