tags:

views:

681

answers:

3

I'm trying to make a select that calculates affiliate payouts.

my approach is pretty simple.

SELECT
 month(payments.timestmap)
,sum(if(payments.amount>=29.95,4,0)) As Tier4
,sum(if(payments.amount>=24.95<=29.94,3,0)) As Tier3
,sum(if(payments.amount>=19.95<=24.94,2,0)) As Tier2
FROM payments
GROUP BY month(payments.timestamp)

The above does not work because MySQL is not evaluating the second part of the condition. Btw it does not cause a syntax error and the select will return results.

Before the above I tried what I was assuming would work like "amount between 24.94 AND 29.94" this caused an error. so then I tried "amount >= 24.94 AND <= 29.94"

So is it possible to have a range comparison using IF in MySql?

+3  A: 

The second part of the expression evaluates when you use AND -

SELECT
 month(payments.timestmap)
,sum(if(payments.amount>=29.95,4,0)) As Tier4
,sum(if(payments.amount>=24.95 AND payments.amount<=29.94,3,0)) As Tier3
,sum(if(payments.amount>=19.95 AND payments.amount<=24.94,2,0)) As Tier2
FROM payments
GROUP BY month(payments.timestamp)

I'm not entirely sure why the between clause didn't work for you, but the above should do the job.

ConroyP
where as "accept as answer"?
Brian Boatright
It should appear for you beside the grey links under each post, "accept answer" or the like I think - been a while since I've asked a question!
ConroyP
I swear it is not there at the moment. i've asked a few questions and accepted answers before. maybe it is in transition or something but I do not see it. did a FF search on the page and accept or answer is not to be found.
Brian Boatright
it just came back. I submitted a uservoice and suddenly it reappeared... maybe there is a timer/delay or someone noticed my uservoice and knew what happened.
Brian Boatright
That is strange alright. Still, main thing is that your problem got solved!
ConroyP
true and thanks for such a quick and informative answer. this is what is great about SO!
Brian Boatright
A: 

There is always the BETWEEN...AND... operator in MySQL.

Thomas Owens
+1  A: 

What error did your first attempt give you? It should definitely work. However, note that the second form you have is incorrect syntax. It should be amount >= 24.94 and amount <= 29.94.

KernelM
you and PConroy are right, duh on my part. I should have added the column name as part of the 2nd condition.
Brian Boatright