mysql 如何?oracle中decode(…)函數的功能

來源:互聯網
上載者:User

       在資料抓取的過程中遇到了在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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.