开发者社区> 问答> 正文

'SELECT'语句中的'IF'-根据列值选择输出值

SELECT id, amount FROM report 我需要的amount是amount,如果report.type='P'和-amount如果report.type='N'。如何将此添加到上面的查询中?

展开
收起
保持可爱mmm 2020-05-10 18:40:32 354 0
1 条回答
写回答
取消 提交回答
  • SELECT id, IF(type = 'P', amount, amount * -1) as amount FROM report 参见http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html。

    此外,您可以处理条件为null的情况。如果为零:

    SELECT id, IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM report 该部分IFNULL(amount,0)表示当金额不为null时返回金额,否则返回0。

    2020-05-10 18:40:47
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载