mysql if--else

來源:互聯網
上載者:User

標籤:相對   部分   兩種   case when   rom   對比   返回   sql   too   

case具有兩種格式。簡單case函數和case搜尋函數。

--簡單case函數case sex  when ‘1‘ then ‘男‘  when ‘2‘ then ‘女’  else ‘其他‘ end--case搜尋函數case when sex = ‘1‘ then ‘男‘     when sex = ‘2‘ then ‘女‘     else ‘其他‘ end  

這兩種方式,可以實現相同的功能。簡單case函數的寫法相對比較簡潔,但是和case搜尋函數相比,功能方面會有些限制,比如寫判定式。

 

還有一個需要注重的問題,case函數只返回第一個合格值,剩下的case部分將會被自動忽略。

--比如說,下面這段sql,你永遠無法得到“第二類”這個結果case when col_1 in (‘a‘,‘b‘) then ‘第一類‘     when col_1 in (‘a‘) then ‘第二類‘     else ‘其他‘ end  

下面執行個體示範:

3、將sum與case結合使用,可以實現分段統計。
     如果現在希望將上表中各種性別的人數進行統計,sql語句如下:

SQL> select  2    sum(case u.sex when 1 then 1 else 0 end)男性,  3    sum(case u.sex when 2 then 1 else 0 end)女性,  4    sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性別為空白  5  from users u;         男性         女性       性別為空白---------- ---------- ----------         3          2          0--------------------------------------------------------------------------------SQL> select  2    count(case when u.sex=1 then 1 end)男性,  3    count(case when u.sex=2 then 1 end)女,  4    count(case when u.sex <>1 and u.sex<>2 then 1 end)性別為空白  5  from users u;         男性          女       性別為空白---------- ---------- ----------         3          2          0

 

mysql if--else

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.