web-dev-qa-db-fra.com

'IF' dans l'instruction 'SELECT' - choisissez une valeur de sortie en fonction des valeurs de colonne

SELECT id, amount FROM report

J'ai besoin de amount pour être amount si report.type='P' et -amount si report.type='N'. Comment puis-je ajouter ceci à la requête ci-dessus?

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

Voir http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html .

En outre, vous pouvez gérer lorsque la condition est null. Dans le cas d'un montant nul:

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

La partie IFNULL(amount,0) signifie lorsque le montant n'est pas nul. Return return sinon renvoie 0 .

990
Felipe Buccioni

Utilisez une instruction case:

select id,
    case report.type
        when 'P' then amount
        when 'N' then -amount
    end as amount
from
    `report`
241
mellamokb
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;
93
user1210826
select 
  id,
  case 
    when report_type = 'P' 
    then amount 
    when report_type = 'N' 
    then -amount 
    else null 
  end
from table
37
sang kaul

Le moyen le plus simple consiste à utiliser un IF () () . Oui Mysql vous permet de faire de la logique conditionnelle. Si la fonction prend 3 paramètres CONDITION, TRUE OUTCOME, FALSE OUTCOME.

Donc, la logique est

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

Vous pouvez sauter abs () si tous les non sont seulement + ve

14
aWebDeveloper
SELECT id, amount
FROM report
WHERE type='P'

UNION

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

ORDER BY id;
11
linitux

Essayons celui-ci:

 SELECT
    id , IF(report.type = 'p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
 FROM report
4
Shashank Singh

Vous pouvez essayer aussi

 Select id , IF(type=='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount from table
2
Basant Rules