mysql 如何实现oracle中decode(...)函数的功能

        在数据抓取的过程中遇到了在sql语句中实现选择判断的需求,参考原来的脚本发现其中有一个 DECODE(value, if1, then1, if2,then2, if3,then3, . . . else )函数可以实现这种需求,拿过来用上后报错,一查发现这个函数在oracle数据里可以使用,mySql数据库就不能使用了,那么mysql该如何实现呢,网上的资料很多,只要找出问题,解决的办法网上一般都会找到,下面就介绍我用的办法。
举例:
oracle中(decode):
SELECT sum(sti.find_questions) as findtotal,
       sum(sti.update_questions) as updatetotal,
       round(100 * ((decode(sum(sti.update_questions), null, 0, sum(sti.update_questions))) / ((decode(sum(sti.update_questions), null, 0, sum(sti.update_questions)))) as zgl_0 
   FROM yujing.special_task_inspect sti 
   where task_id = ? 
         and sti.inspect_time >= ? 
         and sti.inspect_time <= ?
对应mysql中(select case when *** then *** else *** end):
SELECT sum(sti.find_questions) as findtotal,
       sum(sti.update_questions) as updatetotal,
       round(100 *
             ((select case
                        when sum(sti.update_questions) = null then
                         0
                        else
                         sum(sti.update_questions)
                      end) / (select case
                                        when sum(sti.find_questions) = null then
                                         0
                                        else
                                         sum(sti.find_questions)
                                      end))) as zgl_0
  FROM yujing.special_task_inspect sti
 where task_id = ?
   and sti.inspect_time >= ?
   and sti.inspect_time <= ?

总结:只要找到了问题的关键点,解决问题就会变的很容易。

此外,还可以在Order by中使用Decode

例如:表table_subject,有subject_name列。要求按照:语、数、外的顺序进行排序。这时,就可以非常轻松的使用Decode完成要求了。

select * from table_subject order bydecode(subject_name, '语文', 1, '数学', 2, '外语',3)



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值