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

Choose output value based on column values- use of 'IF' in 'SELECT' statement

SELECT id, amount FROM report
I need amount to be calculated if report.type='P' and -amount if report.type='N'.
How to add this to the above query?
by

3 Answers

kshitijrana14
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.
RoliMishra
Use a case statement:

select id,
case report.type
when 'P' then amount
when 'N' then -amount
end as amount
from
`report`
pankajshivnani123

select
id,
case
when report_type = 'P'
then amount
when report_type = 'N'
then -amount
else null
end
from table

Login / Signup to Answer the Question.