Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 432 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'IF' in 'SELECT' statement - choose output value based on column values

#1
SELECT id, amount FROM report

I need `amount` to be `amount` if `report.type='P'` and `-amount` if `report.type='N'`. How do I add this to the above query?
Reply

#2
Use a `case` statement:

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

#3
SELECT CompanyName,
CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
WHEN Country = 'Brazil' THEN 'South America'
ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;
Reply

#4
SELECT id, amount
FROM report
WHERE type='P'

UNION

SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'

ORDER BY id;
Reply

#5
Most simplest way is to use a [IF()][1]. Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

So Logic is


if report.type = 'p'
amount = amount
else
amount = -1*amount

**SQL**

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


You may skip abs() if all no's are +ve only

[1]:

[To see links please register here]

Reply

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

#7
You can try this also

SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table
Reply

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

See

[To see links please register here]

.

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*.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through