0

I am doing a report whereby I can't construct the SQL programatically. I have two values that are fed into the report. The values that can be one of the following three options:

  1. redeem
  2. purchase
  3. redeem AND purchase

The query needs to have a WHERE clause. If "redeem" is fed in, it must have:

... WHERE balance < 0

If "purchase" is fed in, it must have:

... WHERE balance >= 0

if both are fed in, this condition can be left out completely, or it can be said:

... WHERE balance >= 0 OR balance < 0 --> but this is redundant

Is there a way to apply this kind of logic in SQL? Is something like this possible in SQL:

SELECT * FROM account WHERE (if param1 = 'redeem' then 'balance <= 0)  ... etc

?

1

4 Answers 4

3

Yep. You're almost there.

WHERE (param='redeem' and balance <=0) or (param='purchase' and balance>=0) or (param='redeem AND purchase ')
Sign up to request clarification or add additional context in comments.

2 Comments

+1 This is the only correct answer I believe -- and here you go (sqlfiddle.com/#!2/865d1/1) (although you can probably remove the last check)
Just noe that the param = 'redeem AND purchase' part is not correct. I used: param1 = "redeem" AND param2 = "purchase" etc
1

Use CASE statements in your WHERE clause. You can find examples here.

I tried the following code in MySQL and it works:

SET @param = 'purchase';

SELECT * FROM TEST.ACCOUNT
WHERE CASE
    WHEN @param = 'redeem' THEN BALANCE < 0
    WHEN @param = 'purchase' THEN BALANCE >= 0
    ELSE TRUE
END;

3 Comments

-1 You need to post the relevant code here in case the link goes dead.
For this specific case, I do not believe you can use CASE statements (easily). Please show how if I'm mistaken.
I've added code that should work... Please tell me if I'm wrong.
0

Would this do the trick?

WHERE 
   (purchase is not null && balance >= 0)
OR
   (redeem is not null && balance < 0)

Comments

0
CASE WHEN param1 = 'redeem' THEN balance <= 0

1 Comment

why there is a quote before balance ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.