tags:

views:

35

answers:

4

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.

+1  A: 

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.

Thomas
+1  A: 
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)
RedFilter
+1: I think this is what Gugu is after
OMG Ponies
this doesn't work
Gugu
@Gugu: Can you please update your question to include example data and expected output, so it's more clear to us what you're after?
OMG Ponies
@Gugu: Post the exact statement you are running, along with your schema, anf explain **how** it's not working. Also, see my update.
RedFilter
A: 

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.

Gugu
This isn't a forum. Please post any updates to your question by `edit` ing the original question. Also, delete this "answer".
VeeArr
@VeeArr: Gugu is a brand new account, and can't leave comments.
OMG Ponies
sorry i am new to stackoverflow
Gugu
@Poines: He should be able to edit his own questions, if I am not mistaken? @Gugu: It's okay, everyone has to start somewhere. :)
VeeArr
A: 
SELECT SUM(IF(<condition1>, 
              IF(<condition2>,
                 <field1>,
                 <field2>),
              <field2>)) AS total_value
VeeArr
not working, geting same resuls as with one condition
Gugu
You should update your original question to clarify exactly what it is you are looking to get.
VeeArr