“如果”在“选择”语句中-根据列值选择输出值

从报告中选择id、金额

我需要amount成为amountifreport.type='p'-amountifreport.type='N'。如何将其添加到上述查询中

选择id,
如果(类型='P',金额,金额*-1)作为金额
来自报告

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

此外,您可以在条件为null时处理。如果金额为空:

选择id,
如果(类型='P',IFNULL(金额,0),IFNULL(金额,0)*-1)作为金额
来自报告

部分IFNULL(amount,0)表示当amount不为null时返回amount,否则返回0

发表评论