Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

'IF' in 'SELECT' statement - choose output value based on column values

SELECT id, amount FROM report


I need add up to be sum if report.type='P' and - sum if report.type='N'. How would I add this to the above question?
by

2 Answers

espadacoder11

SELECT id,
IF(type = 'P', amount, amount -1) as amount
FROM report


Additionally, you could handle when the condition is null. In the case of a null amount:

SELECT id,
IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0)
-1) as amount
FROM report

The part IFNULL(amount,0) means when amount is not null return amount else return 0.
kshitijrana14
Use a case statement:
select id,
case report.type
when 'P' then amount
when 'N' then -amount
end as amount
from
`report`

Login / Signup to Answer the Question.