开发者

Doing sum's if certain conditions are true

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

SE开发者_C百科LECT 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.


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.


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)


SELECT SUM(IF(field = value1 OR field = value2 OR field = value3,1,NULL)) AS total_value


SELECT SUM(IF(<condition1>, 
              IF(<condition2>,
                 <field1>,
                 <field2>),
              <field2>)) AS total_value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜