6

I have a table with type field.

how can I check this field in query:

I want to check it if type == 'a'

then bes=amount,bed = '-'

ELSE bed=amount,bes = '-'

bes and bed is not really exists in my table but amount is (int)

this is my try:

SELECT billing.*,
    CASE billing.type WHEN 'A' THEN billing.amount AS bes, '-' AS bed ELSE billing.amount AS bed, '-' AS bes END
    FROM billing

... my searches wasn't useful

any solution...

3
  • As you can see, we are all very much in agreement about the proper solution here :-) Commented Mar 11, 2013 at 13:38
  • thats good... when I try this in separate query, there is no problem but in my project ... error Commented Mar 11, 2013 at 13:59
  • What error are you getting? Commented Mar 11, 2013 at 14:06

5 Answers 5

8

You can create condition for every row, MySQL supports inline IF statements.

SELECT billing.*,
       IF(billing.type = 'A', billing.amount, '-') AS bes,
       IF(billing.type = 'A', '-', billing.amount) AS bed
FROM   billing
Sign up to request clarification or add additional context in comments.

Comments

4

You'll need two case statements for that:

SELECT billing.*,
  CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' AS bes END,
  CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount AS bed END
FROM billing

Comments

3

One CASE-WHEN-THEN-ELSE can have only one return value...

This should do the trick:

SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' END AS bes,
CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount END AS bed 
FROM billing

Comments

3
SELECT billing.*,
    CASE  WHEN billing.type =  'A' THEN billing.amount ELSE 0 END AS bes,
    CASE  WHEN billing.type <> 'A' THEN billing.amount ELSE 0 END AS bed
FROM billing

Comments

2

Depending on your MySQL version, you can use IF or one of two different syntaxes for CASE CASE(1), CASE(2).

SELECT *,
  (IF type = 'A' THEN amount ELSE '-' END IF) bes,
  (IF type = 'A' THEN '-' ELSE amount END IF) bed
FROM billing

Comments

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.